Python3 math.ceil()、math.floor()、//、int()、round()取整问题
1. 向上取整:math.ceil(),往较大的方向取
import math
math.ceil(2.1)
3
math.ceil(2.8)
3
math.ceil(-2.1)
-2
math.ceil(-2.9)
-2
2. 向下取整:math.floor(),往较小方向取
math.floor(2.1)
2
math.floor(2.9)
2
math.floor(-2.1)
-3
math.floor(-2.9)
-3
3. // 取整:往小的方向取
3//2
1
-3//2
-2
注意:若被除数为小数(float型),则结果也为小数(float型)
3.0//2
1.0
4.2//2
2.0
4. int() 取整:往 0 的方向取
int(2.1)
2
int(2.9)
2
int(-2.1)
-2
int(-2.9)
-2
5. round() 取整:四舍五入
round(2.1)
2
round(2.5)
2
round(2.6)
3
分析:发现 round()
的四舍五入对边界 .5
的处理与预判不一致,原因为 2.5
或 2.50
存储时为 2.449
,round()
四舍五入看小数点后第一位,因此结果为 2。
round(2.51) # 2.51 进位
3
负数情况同上:
round(-2.1)
-2
round(-2.5)
-2
round(-2.51)
-3
round(-2.6)
-3
指定小数点位数:
round(2.6666)
3
round(2.6666, 0) # 默认为 0 的整数,设置为 0 得到值相同浮点数
3.0
round(2.6666, 1)
2.7
round(2.6666, 2)
2.67
round(2.6666, 3)
2.667
注意:上示例 2.5
或 2.50
存储为 2.449
并不是所有 .5
情况都为 .449
,需要进一步查阅相关资料(望大佬赐教,非常感谢)。
print(round(0.5), round(1.5), round(2.5))
0 2 2
print(round(0.675,2), round(1.675,2), round(2.675,2))
0.68 1.68 2.67
参考: