Python math.ceil() 方法



Python 的 math.ceil() 方法用於查詢數值的最近大於等於它的整數。例如,浮點數 3.6 的 ceil 值為 4。

此過程與估算或四捨五入技術非常相似。區別在於 3.6 的 ceil 值為 4,但 3.2 的 ceil 值也為 4;與估算技術不同,估算技術將 3.2 四捨五入為 3 而不是 4。

注意 - 此函式無法直接訪問,因此我們需要匯入 math 模組,然後使用 math 靜態物件呼叫此函式。

語法

以下是 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

示例

但是,此方法不會接受數值物件以外的任何值作為其引數。

在此示例中,讓我們嘗試將包含數值物件的列表作為引數傳遞給此方法,並檢查它是否為所有物件計算了 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

示例

要使用此方法返回列表中數值物件的 ceil 值,可以使用迴圈語句。

我們正在建立一個包含數字物件的列表,其 ceil 值將使用 ceil() 方法計算。然後,我們將使用 for 迴圈迭代此列表;對於每次迭代,列表中的數字物件都將作為引數傳遞給此方法。由於列表中的物件都是數字,因此該方法不會引發錯誤。

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

示例

我們可以在 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
python_maths.htm
廣告區域