先上具体的例子:
脚本中附加了math.ceil函数(和math.floor对立)
root@pts/4 $ cat python_math_floor_and_trunc.py #!/usr/bin/env pyton #-*- codingL utf-8 -*- import math a = 3 b = 3.12 c = 3.67 print('-'*20+'a = 3; b = 3.12; c = 3.67'+'-'*20) print('-'*20+'math.ceil a b c'+'-'*20) print(math.ceil(a)) print(math.ceil(b)) print(math.ceil(c)) print('-'*20+'math.floor a b c'+'-'*20) print(math.floor(a)) print(math.floor(b)) print(math.floor(c)) print('-'*20+'math.trunc a b c'+'-'*20) print(math.trunc(a)) print(math.trunc(b)) print(math.trunc(c))在Python2.7下的运行结果是:
root@pts/4 $ python python_math_floor_and_trunc.py --------------------a = 3; b = 3.12; c = 3.67-------------------- --------------------math.ceil a b c-------------------- 3.0 4.0 4.0 --------------------math.floor a b c-------------------- 3.0 3.0 3.0 --------------------math.trunc a b c-------------------- 3 3 3在Python3.5下的运行结果是:
root@pts/5 $ python python_math_floor_and_trunc.py --------------------a = 3; b = 3.12; c = 3.67-------------------- --------------------math.ceil a b c-------------------- 3 4 4 --------------------math.floor a b c-------------------- 3 3 3 --------------------math.trunc a b c-------------------- 3 3 3 总结来说: math.trunc 不管是在Python2.7或者是Python3.5版本中最终的结果都是`截断`之后的`整数` math.ceil/math.floor 在Python2.7版本返回值是`浮点数`;在python3.5版本是`整数` math.ceil 是返回 大于或者等于当前值的`最小整数` math.floor 是返回 小于或者等于当前值的`最大整数`