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

pythonserver side programmingprogramming更新于 2025/9/23 19:56:17

这两个方法是 Python 数学模块的一部分,有助于获取小数的最近整数值。

floor()

它接受一个带有小数的数字作为参数,并返回小于该数字本身的整数。

语法

语法:floor(x)
其中 x 是一个数值

floor() 示例

在下面的例子中,我们采用不同类型的数值,如整数、正小数和负小数,并对它们应用 floor 函数。我们得到小于所提供数值的最接近的整数。

import math
x,y,z = 21 , -23.6 , 14.2
print("The value of ",x, "on applying floor() function is:", math.floor(x))
print("The value of ",y, "on applying floor() function is:", math.floor(y))
print("The value of ",z, "on applying floor() function is:", math.floor(z))

输出

运行上述代码得到以下结果 −

The value of 21 on applying floor() function is: 21
The value of -23.6 on applying floor() function is: -24
The value of 14.2 on applying floor() function is: 14

ceil()

它接受一个带有小数的数字作为参数,并返回大于该数字本身的整数。

语法

语法:veil(x)
其中 x 是一个数值

ceil() 示例

在下面的例子中,我们采用不同类型的数值,如整数、正小数和负小数,并对它们应用 ceil 函数。我们得到最接近的整数,该整数大于提供的数值。

import math
x,y,z = 21 , -23.6 , 14.2
print("The value of ",x, "on applying ceil() function is:", math.ceil(x))
print("The value of ",y, "on applying ceil() function is:", math.ceil(y))
print("The value of ",z, "on applying ceil() function is:", math.ceil(z))

输出

运行上述代码得到以下结果 −

The value of 21 on applying ceil() function is: 21
The value of -23.6 on applying ceil() function is: -23
The value of 14.2 on applying ceil() function is: 15

相关文章


有用资源