python判斷正負(fù)數(shù)方式
我就廢話不多說(shuō)了,大家還是直接看代碼吧!
a1 = raw_input('please input a number')a = int(a1)if(a!=0):if(a > 0):print ’這是正數(shù)’if(a < 0 ):print ’這是負(fù)數(shù)’else:print ’the number is equal to 0’
補(bǔ)充知識(shí):判斷一個(gè)數(shù)值是否為正數(shù)、負(fù)數(shù)、零、整數(shù)
最近在看阮一峰老師的《ES6標(biāo)準(zhǔn)入門(mén)》的時(shí)候,看到ES6新增了兩個(gè)方法。
用來(lái)判斷一個(gè)數(shù)值。
一、判斷整數(shù)------Number.isInteger()
Number.isInteger() 首先判斷該值是否為number類(lèi)型,不是直接返回false;
是number類(lèi)型的話在判斷是否為整數(shù)。
Number.isInteger(25); //trueNumber.isInteger(25.222); //falseNumber.isInteger(’25’); // falseNumber.isInteger(’25.222’); //falseNumber.isInteger(’foo’); // false
用Es5來(lái)判斷是否為正數(shù)也很簡(jiǎn)單,實(shí)現(xiàn)方法有很多種,這里列出兩種:
1、利用 Math.round,利用四舍五入來(lái)判斷該值是否為整數(shù)。
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);}
二、判斷一個(gè)數(shù)是否為正數(shù)、負(fù)數(shù)、或者零----Math.sign()
返回5種值:
+1 正數(shù)
-1 負(fù)數(shù)
0 0
-0 -0
NaN 其他值
console.log(Math.sign(-5)); //-1console.log(Math.sign(-5.222)); // -1console.log(Math.sign(555)); // 1console.log(Math.sign(0)); // 0console.log(Math.sign(-0)); // -0console.log(Math.sign(’foo’)); // NaN
Es5實(shí)現(xiàn)方法:
Math.sign = Math.sign || function (n){ n = +n; if(n === 0 || isNaN(n)){ return n; } return x > 0 ? 1 : -1;}
以上這篇python判斷正負(fù)數(shù)方式就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
