萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Python math.floor() 函數教學:向下取整取得不大於 x 的最大整數

math.floor() 回傳不大於 x 的最大整數(向下取整),結果以浮點數型態呈現。本文說明語法、參數、回傳值與範例。

模組匯入

import math

函數語法

math.floor(x)

參數說明

  • x:數值運算式。

回傳值

回傳不大於 x 的最大整數(浮點數)。

程式碼範例

#!/usr/bin/python
import math
print "math.floor(-45.17) : ", math.floor(-45.17)
print "math.floor(100.12) : ", math.floor(100.12)
print "math.floor(100.72) : ", math.floor(100.72)
print "math.floor(119L) : ", math.floor(119L)
print "math.floor(math.pi) : ", math.floor(math.pi)

執行結果

math.floor(-45.17) : -46.0
math.floor(100.12) : 100.0
math.floor(100.72) : 100.0
math.floor(119L) : 119.0
math.floor(math.pi) : 3.0

比較: int(-45.17) 會直接截斷回傳 -45,而 floor() 則正確向下取整為 -46。

copyright © 萬盛學電腦網 all rights reserved