Python math.ceil() 方法用于查找最接近的数值的较大整数。例如,浮点数 3.6 的 ceil 值为 4。
所涉及的过程几乎类似于估计或四舍五入技术。当 ceil 值 3.6 为 4 时出现差异,但 ceil 值 3.2 也将为 4;与估计技术不同,后者将 3.2 四舍五入为 3 而不是 4。
注意 − 这个函数不能直接访问,所以我们需要导入 math module,然后我们需要使用 math static object 调用这个函数。
语法
以下是 Python math.ceil() 方法的语法 -
math.ceil(x)
参数
- x − 这是一个数值对象。
返回值
此方法返回大于参数 x 的最小整数。
例以下示例显示了 Python math.ceil() 方法的用法。在这里,我们将创建两个具有正值和负值的数值对象,并且这两个对象的 ceil 值都是使用此方法计算的。
import math # This will import math module
# Create two numeric objects x and y
x = 45.17
y = -36.89
# Calculate and display the ceil value of x
res = math.ceil(x)
print("The ceil value of x:", res)
# Calculate and display the ceil value of y
res = math.ceil(y)
print("The ceil value of y:", res)
当我们运行上述程序时,它会产生以下结果——
The ceil value of x: 46
The ceil value of y: -36
The ceil value of y: -36
例
但是,此方法不会接受除数字对象以外的任何值作为其参数。
在这个例子中,让我们尝试将一个包含数字对象的列表作为参数传递给此方法,并检查它是否计算了所有对象的 ceil 值。
import math # This will import math module
# Create a list containing numeric objects
x = [12.36, 87.45, 66.33, 12.04]
# Calculate the ceil value for the list
res = math.ceil(x)
print("The ceil value of x:", res)
在执行上述程序时,将引发 TypeError ,如下所示 -
Traceback (most recent call last):
File "main.py", line 5, in
res = math.ceil(x)
TypeError: must be real number, not list
File "main.py", line 5, in
res = math.ceil(x)
TypeError: must be real number, not list
例
要使用此方法返回列表中数字对象的 ceil 值,可以使用 loop 语句。
我们正在创建一个包含 number 对象的列表,其 ceil 值将使用 ceil() 方法计算。然后,我们将使用 for 循环迭代此列表;对于每次迭代,列表中的 Number 对象将作为参数传递给此方法。由于列表中的对象都是数字,因此该方法不会引发错误。
import math # This will import math module
# Create a list containing numeric objects
x = [12.36, 87.45, 66.33, 12.04]
ln = len(x)
# Calculate the ceil value for the list
for n in range (0, ln):
res = math.ceil(x[n])
print("The ceil value of x[",n,"]:", res)
现在,如果我们执行上面的程序,结果将产生如下 -
The ceil value of x[ 0 ]: 13
The ceil value of x[ 1 ]: 88
The ceil value of x[ 2 ]: 67
The ceil value of x[ 3 ]: 13
The ceil value of x[ 1 ]: 88
The ceil value of x[ 2 ]: 67
The ceil value of x[ 3 ]: 13
例
我们可以在 Python 的许多实际应用中实现这个功能。例如,让我们尝试找到两个数字的商的 ceil 值。让我们首先创建两个数字对象,使用 “/” 运算符将它们除以,并使用 ceil() 方法找到它们的商的 ceil 值。
import math # This will import math module
# Create a list containing numeric objects
x = 54.13
y = 14.78
#Find the quotient of x and y
qt = x/y
print("The quotient of these values is:", qt)
# Calculate the ceil value for the quotient
res = math.ceil(qt)
print("The ceil value of x/y is:", res)
让我们编译并运行上面的程序,输出显示如下 -
The quotient of these values is: 3.6623815967523683
The ceil value of x/y is: 4
The ceil value of x/y is: 4