Python 向下取整

Python 向下取整语法

在 Python 中,我们可以使用 math 模块的 floor() 函数对一个数进行向下取整。所谓 “向下取整”,指的是返回小于或等于指定数的最大整数。

语法:

math.floor(x)

说明:

math.floor(x) 表示返回小于或等于 x 的最大整数。

提示: math.floor() 实现的是 “向下取整” ,而 math.ceil() 实现的是 “向上取整” 。

Python 向下取整示例

接下来,我们通过一个简单的例子来讲解 Python 向下取整是如何实现的。

示例:Python 实现向下取整

import math

print('math.floor(3):', math.floor(3))
print('math.floor(0.4):', math.floor(0.4))
print('math.floor(0.6):', math.floor(0.6))
print('math.floor(-1.1):', math.floor(-1.1))
print('math.floor(-1.9):', math.floor(-1.9))

运行结果如下。

math.floor(3): 3
math.floor(0.4): 0
math.floor(0.6): 0
math.floor(-1.1): -2
math.floor(-1.9): -2

分析:

从上面示例可以看出:在 math.floor(x) 中,如果 x 为整数,则返回 x;如果 x 为小数,则返回小于 x 的最近的那个整数。这就是所谓的 “向下取整”,分析如下图所示。

Python 向下取整

上一篇: Python 向上取整

下一篇: Python 四舍五入

给站长反馈

绿叶网正在不断完善中,小伙伴们如果发现任何问题,还望多多给站长反馈,谢谢!

邮箱:lvyenet@vip.qq.com

「绿叶网」服务号
绿叶网服务号放大
关注服务号,微信也能看教程。
绿叶网服务号