哑哑 发表于 2024-7-16 18:04:19

Python教程:ceil、floor、round、int取整

1.向上取整 math.ceil

math.ceil() 严格遵循向上取整,所有小数都向着数值更大的方向取整。
import math
math.ceil(-1.5) # -1
math.ceil(1.5) # 2
math.ceil(-0.9) # 02.向下取整 math.floor

同 math.ceil 类似,方向相反,向下取整。
import math
math.floor(-0.5) # -1
math.floor(1.6) # 13.四舍五入 round

round() 方法返回浮点数的四舍五入值。
使用语法:
round(x, [, n])
x -- 浮点数
n -- 小数点位数实操:
round(1.5) # 2
round(-1.5) # -2
round(-0.5) # 0
round(0.5) # 0
round(2.5) # 2
round(100.5132, 2) # 100.51不传第二个参数时,默认取整,四舍五入
小数末尾为5的处理方法:

[*]末尾为5的前一位为奇数:向绝对值更大的方向取整
[*]末尾为5的前一位为偶数:去尾取整
round只是针对小数点后.5的情况会按照规律计算,因为存储时不同,例如:4.5存储时为4.4999999...
4.取整 int

int() 向0取整,取整方向总是让结果比小数的绝对值更小。
#Python学习交流群:725638078
int(-0.5) # 0
int(-0.9) # 0
int(0.5) # 0
int(1.9) # 15.整除 //

”整除取整“符号运算实现向下取整,与 math.floor() 方法效果一样。
-1 // 2 # -1
-3 // 2 # -2
101 // 2 # 50
3 // 2 # 1
来源:https://www.cnblogs.com/python1111/p/18305356
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!
页: [1]
查看完整版本: Python教程:ceil、floor、round、int取整