round(),math.ceil(),math.floor()的區別
-
- round():round 是“附近、周圍”的意思,所以該函數是一個求近似值的函數,用四捨五入法(有特例)。例子如下:
# 正數: 四捨五入
import math
round(11.46) # 結果:11
round(11.56) # 結果:12
# 負數: 取絕對值後四捨五入,再變回負數
round(-11.46) # 結果:-11
round(-11.56) # 結果:-12
# 小數部分是 .5 時需注意,結果取最接近的偶數(特例)
round(11.5) # 結果:12
round(10.5) # 結果:10
round(-11.5) # 結果:-12
round(-10.5) # 結果:-10
-
- math.ceil():ceil 是“天花板”的意思,所以該函數是求較大數的,用進一法。例子如下。
import math
# 如果小數部分非0, 則取整加1
math.ceil(11.46) # 結果: 12
math.ceil(-11.46) # 結果: -11
-
- math.floor():floor”有“地板”的意思,所以該函數是取較小數,和ceil函數相反。例子如下。
import math
math.floor(11.46) # 結果: 11
math.floor(-11.46) # 結果: -12