2-5 無條件進位及無條件捨去

如果要將浮點數的小數位進行無條件進位或無條件捨去的動作,可以使用Python的math模組中的內建函式ceil()floor()完成它。

程式:
import math  #匯入math模組

a = 16.1 / 4
b = math.ceil(16.1 / 4)    #無條件進位
c = math.floor(16.1 / 4)   #無條件捨去

print(a)
print(b)
print(c)
執行結果:
4.025
5
4

math是Python的一個模組,其中有許多與數學相關的函式可以使用。例如ceil()floor(),就是math中提供作為計算無條件捨去及無條件進位的函式。不管是ceil()或是floor(),它們的運算結果會以整數型態儲存。

circle-info

ciil的全稱是ceiling,代表天花板,作用是無條件進位;floor則是代表地板,作用是無條件捨去。

Last updated