python對一個(gè)數(shù)向上取整的實(shí)例方法
python中向上取整可以用ceil函數(shù),ceil函數(shù)是在math模塊下的一個(gè)函數(shù)。
向上取整需要用到 math 模塊中的 ceil() 方法:
>>> import math>>> math.ceil(3.25)4.0>>> math.ceil(3.75)4.0>>> math.ceil(4.85)5.0
分別取整數(shù)部分和小數(shù)部分
有時(shí)候我們可能需要分別獲取整數(shù)部分和小數(shù)部分,這時(shí)可以用 math 模塊中的 modf() 方法,該方法返回一個(gè)包含小數(shù)部分和整數(shù)部分的元組:
>>> 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)
知識點(diǎn)擴(kuò)展:
python對數(shù)字的四種取整方法:int,ceil,round,modf
# int(): 向下取整3.7取3;# math.ceil(): 向上取整3.2取4;# round(): 四舍五入;# math.modf(): 取整數(shù)部分和小數(shù)部分,返回一個(gè)元組:(小數(shù)部分,整數(shù)部分)。注意小數(shù)部分的結(jié)果有異議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)'''
到此這篇關(guān)于python對一個(gè)數(shù)向上取整的實(shí)例方法的文章就介紹到這了,更多相關(guān)python如何對一個(gè)數(shù)向上取整內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. Python+unittest+requests 接口自動(dòng)化測試框架搭建教程2. Python的文本常量與字符串模板之string庫3. 利用CSS制作3D動(dòng)畫4. 存儲(chǔ)于xml中需要的HTML轉(zhuǎn)義代碼5. 完美解決vue 中多個(gè)echarts圖表自適應(yīng)的問題6. jsp+servlet簡單實(shí)現(xiàn)上傳文件功能(保存目錄改進(jìn))7. 一款功能強(qiáng)大的markdown編輯器tui.editor使用示例詳解8. .Net加密神器Eazfuscator.NET?2023.2?最新版使用教程9. Java GZip 基于內(nèi)存實(shí)現(xiàn)壓縮和解壓的方法10. SpringBoot+TestNG單元測試的實(shí)現(xiàn)
