+关注继续查看

# math.floor() & math.trunc()

## math.floor 和 math.trunc的官方不同版本的介绍如下：

math.floor:
python2.7:  Return the floor of x as a float, the largest integer value less than or equal to x.
python3.5:  Return the floor of x, the largest integer less than or equal to x. If x is not a float, delegates to x.__floor__(), which should return an Integral value.

math.trunc:
python2.7:  Return the Real value x truncated to an Integral (usually a long integer). Uses the __trunc__ method.
python3.5:  Return the Real value x truncated to an Integral (usually an integer). Delegates to x.__trunc__().

math.ceil:
python2.7:  Return the ceiling of x as a float, the smallest integer value greater than or equal to x.
python3.5:  Return the ceiling of x, the smallest integer greater than or equal to x. If x is not a float, delegates to x.__ceil__(), which should return an Integral value.


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

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 是返回 小于或者等于当前值的最大整数


Python经典编程习题100例：第85例：999除法
Python经典编程习题100例：第85例：999除法
12 0
Python浮点数转整数int、round、ceil、floor
Python浮点数转整数int、round、ceil、floor
47 0
Python除法运算/、//、%、divmod
Python除法运算/、//、%、divmod
30 0
Python - 基本数据处理函数 round()、int()、floor()、ceil()
Python - 基本数据处理函数 round()、int()、floor()、ceil()
43 0
Python---试除法求质数的三种方式对比

1392 0
Python多线程爬虫编程中queue.Queue和queue.SimpleQueue的区别和应用

36 0
Python CGI编程

23 0
Python编程：MySQLdb模块对数据库的基本增删改查操作
Python编程：MySQLdb模块对数据库的基本增删改查操作
35 0
+关注

Python 脚本速查手册

ACE 区域技术发展峰会：Flink Python Table API入门及实践