python判断正负数方式
作者:urllib3 时间:2023-07-06 11:16:12
我就废话不多说了,大家还是直接看代码吧!
a1 = raw_input("please input a number")
a = int(a1)
if(a!=0):
if(a > 0):
print '这是正数'
if(a < 0 ):
print '这是负数'
else:
print 'the number is equal to 0'
补充知识:判断一个数值是否为正数、负数、零、整数
最近在看阮一峰老师的《ES6标准入门》的时候,看到ES6新增了两个方法。
用来判断一个数值。
一、判断整数------Number.isInteger()
Number.isInteger() 首先判断该值是否为number类型,不是直接返回false;
是number类型的话在判断是否为整数。
Number.isInteger(25); //true
Number.isInteger(25.222); //false
Number.isInteger('25'); // false
Number.isInteger('25.222'); //false
Number.isInteger('foo'); // false
用Es5来判断是否为正数也很简单,实现方法有很多种,这里列出两种:
1、利用 Math.round,利用四舍五入来判断该值是否为整数。
function numberIsInteger(n){
if(!Number.isInteger){
return typeof n === 'number' && Math.round(n) === n;
}
return n;
}
2、利用取余。
function numberIsInteger(n){
if(!Number.isInteger){
return typeof n === 'number' && n % 1 === 0;
}
return Number.isInteger(n);
}
二、判断一个数是否为正数、负数、或者零----Math.sign()
返回5种值:
+1 正数
-1 负数
0 0
-0 -0
NaN 其他值
console.log(Math.sign(-5)); //-1
console.log(Math.sign(-5.222)); // -1
console.log(Math.sign(555)); // 1
console.log(Math.sign(0)); // 0
console.log(Math.sign(-0)); // -0
console.log(Math.sign('foo')); // NaN
Es5实现方法:
Math.sign = Math.sign || function (n){
n = +n;
if(n === 0 || isNaN(n)){
return n;
}
return x > 0 ? 1 : -1;
}
来源:https://blog.csdn.net/yunjin386/article/details/54798966
标签:python,判断,正负数
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python3 导入上级目录中的模块实例
2023-09-01 02:25:20
python中MySQLdb模块用法实例
2024-01-25 01:19:27
python基于xml parse实现解析cdatasection数据
2023-08-18 13:27:36
Python3中常见配置文件写法汇总
2022-01-21 11:14:07
![](https://img.aspxhome.com/file/2023/0/110040_0s.png)
python 接口测试response返回数据对比的方法
2023-10-12 14:01:31
拓扑排序Python实现的过程
2021-10-23 13:57:44
![](https://img.aspxhome.com/file/2023/2/66832_0s.png)
Python数据处理pandas读写操作IO工具CSV解析
2021-11-18 23:31:33
![](https://img.aspxhome.com/file/2023/4/109844_0s.png)
OpenCV2从摄像头获取帧并写入视频文件的方法
2022-04-10 07:15:22
Go语言HTTPServer开发的六种方式小结
2023-06-22 21:48:21
关于JDBC与MySQL临时表空间的深入解析
2024-01-22 04:11:14
![](https://img.aspxhome.com/file/2023/7/107907_0s.png)
无忧 月影出书啦《JavaScript王者归来》
2008-01-09 13:45:00
![](https://img.aspxhome.com/file/UploadPic/20081/9/200819135150291s.gif)
MySQL——修改root密码的4种方法(以windows为例)
2024-01-16 17:50:55
python程序运行进程、使用时间、剩余时间显示功能的实现代码
2023-04-14 11:16:33
python中yield的用法详解
2023-06-10 00:43:56
python转化excel数字日期为标准日期操作
2021-01-14 22:38:59
![](https://img.aspxhome.com/file/2023/7/107877_0s.jpg)
一篇文章教你用Python实现一个学生管理系统
2022-01-22 16:25:05
python3 写一个WAV音频文件播放器的代码
2023-04-09 05:06:36
详解微信小程序网络请求接口封装实例
2024-06-12 04:08:54
PyQt5实现进度条与定时器及子线程同步关联
2023-03-20 14:48:35
![](https://img.aspxhome.com/file/2023/5/88875_0s.gif)
python中常用的内置模块汇总
2023-12-28 14:57:01
![](https://img.aspxhome.com/file/2023/3/65573_0s.png)