Python 中的 floor() 和 ceil() 函数

2024 年 8 月 29 日 | 阅读 2 分钟

在本教程中,我们将学习如何在 Python 中使用 math 模块的 floor() 和 ceil() 函数。

floor() 函数

floor() 函数用于获取“X”的向下取整整数,意思是小于或等于“X”的最大整数,基本上是它最近的向下舍入的数字。

语法

参数

我们可以传入数值表达式。

返回值

它返回小于或等于“X”的最大整数。

让我们看一个例子来了解如何在 Python 中实现 floor() 函数。

示例

输出

The floor value of math.floor(-54.21) is:  -55
The floor value of math.floor(432.56) is:  432
The floor value of math.floor(320.62) is:  320

ceil() 函数

Python math 模块的 ceil() 函数用于返回“X”的向上取整值,意思是大于或等于“X”的最小整数,基本上是它最近的向上舍入的数字。

语法

参数

我们可以传入数值表达式。

返回值

它返回大于或等于“X”的最小整数。

让我们看一个例子来了解如何在 Python 中实现 ceil() 函数。

示例

输出

The ceiling value of math.ceil(-54.21) is:  -54
The ceiling value of math.ceil(432.56) is:  433
The ceiling value of math.ceil(320.62) is:  321

结论

在本教程中,我们讨论了如何在 Python 中实现 math 模块的 floor() 和 ceil() 函数。