python對一個數向上取整的實例方法
python中向上取整可以用ceil函數,ceil函數是在math模塊下的一個函數。
向上取整需要用到 math 模塊中的 ceil() 方法:
>>> import math>>> math.ceil(3.25)4.0>>> math.ceil(3.75)4.0>>> math.ceil(4.85)5.0
分別取整數部分和小數部分
有時候我們可能需要分別獲取整數部分和小數部分,這時可以用 math 模塊中的 modf() 方法,該方法返回一個包含小數部分和整數部分的元組:
>>> import math>>> 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 mathflo1 = 3.1415flo2 = 3.500flo3 = 3.789print(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如何對一個數向上取整內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章: