新聞中心
首先,不得不提醒大家一個容易被忽視或者搞混的問題——一般的,0.5這種末尾是5的小數(shù),四舍五入取整應進位。這個進位的意思是:-0.5 → -1;0.5 → 1.即正負情況不同,都向著遠離0,使得絕對值更大的方向進位

向上取整:math.ceil()
import math math.ceil(-0.5) >>> 0 math.ceil(-0.9) >>> 0 math.ceil(0.3) >>> 1
如code所見,math.ceil()嚴格遵循向上取整,所有小數(shù)都是向著數(shù)值更大的方向取整,不論正負數(shù)都如此
四舍五入:round()
round(-2.5) >>> -2 round(-1.5) >>> -2 round(-0.5) >>> 0 round(0.5) >>> 1 round(1.5) >>> 2 round(2.5) >>> 2
如code所示,round()當不傳入第二個參數(shù)時默認取整,具體就是按照四舍五入來。但值得一提的是這里對小數(shù)末尾為5的處理方法:當末尾的5的前一位為奇數(shù):向絕對值更大的方向取整(比如-1.5、1.5處理結果);當末尾的5的前一位為偶數(shù):去尾取整(比如-2.5,-0.5,0.5和2.5的處理結果)。
向下取整:math.floor()
math.floor(-0.3) >>> -1 math.floor(0.9) >>> 0
簡單且忠實地向下取整,不再討論
兩個有趣且特殊的python取整:int()、整除"http://"
int()
int(-0.5) >>> 0 int(-0.9) >>> 0 int(0.5) >>> 0 int(0.9) >>> 0
一句話總結:int()函數(shù)是“向0取整”,取整方向總是讓結果比小數(shù)的絕對值更小
"http://"
(-1) // 2 # -0.5 >>> -1 (-3) // 2 # -1.5 >>> -2 1 // 2 # 0.5 >>> 0 3 // 2 # 1.5 >>> 1
一句話總結:“整除”符號運算將結果忠實地向下取整,與math.floor()處理結果一樣
總結一下:
向上取整:math.ceil()
向下取整:math.floor()、整除"http://"
四舍五入:round()——奇數(shù)向遠離0取整,偶數(shù)去尾取整;或言之:奇數(shù)進位,偶數(shù)去尾
向0取整:int()
當前題目:創(chuàng)新互聯(lián)Python教程:python中如何取整數(shù)
當前路徑:http://www.5511xx.com/article/codcsgi.html


咨詢
建站咨詢
