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


這兩種方法是 Python math 模組的一部分,有助於獲取分數的最近整數。

floor()

它接受一個帶小數的引數,並返回一個小於該數字本身的整數。

語法

Syntax: floor(x)
Where x is a numeric value

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()

它接受一個帶小數的引數,並返回一個大於該數字本身的整數。

語法

Syntax: veil(x)
Where x is a numeric value

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

更新於: 2019年8月8日

2K+ 次瀏覽

開啟你的 職業生涯

完成課程獲得認證

立即開始
廣告

© . All rights reserved.