VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > Python基础教程 >
  • 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) # 0

2.向下取整 math.floor
同 math.ceil 类似,方向相反,向下取整。

import math
math.floor(-0.5) # -1
math.floor(1.6) # 1

3.四舍五入 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取整,取整方向总是让结果比小数的绝对值更小。

int(-0.5) # 0
int(-0.9) # 0
int(0.5) # 0
int(1.9) # 1

5.整除 //
”整除取整“符号运算实现向下取整,与 math.floor() 方法效果一样。

-1 // 2 # -1
-3 // 2 # -2
101 // 2 # 50
3 // 2 # 1

来源:https://www.cnblogs.com/python1111/p/18305356


相关教程