python對一個數向上取整的例項方法
阿新 • • 發佈:2020-06-18
python中向上取整可以用ceil函式,ceil函式是在math模組下的一個函式。
向上取整需要用到 math 模組中的 ceil() 方法:
>>>importmath >>>math.ceil(3.25) 4.0 >>>math.ceil(3.75) 4.0 >>>math.ceil(4.85) 5.0
分別取整數部分和小數部分
有時候我們可能需要分別獲取整數部分和小數部分,這時可以用 math 模組中的 modf() 方法,該方法返回一個包含小數部分和整數部分的元組:
>>>importmath >>>math.modf(3.25) (0.25,3.0) >>>math.modf(3.75) (0.75,3.0) >>>math.modf(4.2) (0.20000000000000018,4.0)
知識點擴充套件:
python對數字的四種取整方法:int,ceil,round,modf
# int(): 向下取整3.7取3; # math.ceil(): 向上取整3.2取4; # round(): 四捨五入; # math.modf(): 取整數部分和小數部分,返回一個元組:(小數部分,整數部分)。注意小數部分的結果有異議 import math flo1 = 3.1415 flo2 = 3.500 flo3 = 3.789 print(int(flo1),math.ceil(flo1),round(flo1),math.modf(flo1)) print(int(flo2),math.ceil(flo2),round(flo2),math.modf(flo2)) print(int(flo3),math.ceil(flo3),round(flo3),math.modf(flo3)) """ int ceil round modf 3 4 3 (0.14150000000000018,3.0) 3 4 4 (0.5,3.0) 3 4 4 (0.7890000000000001,3.0) """
到此這篇關於python對一個數向上取整的例項方法的文章就介紹到這了,更多相關python如何對一個數向上取整內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!