天天看點

python中取整數的幾種方法(python怎麼取整)

大家好,又見面了,我是你們的朋友全棧君。

一、向零取整:int()

python自帶的int()取整

>>> int(1.2)

1

>>> int(2.8)

2

>>> int(-0.1)

>>> int(-5.6)

-5

總結:int()函數是“向0取整”,取整方向總是讓結果比小數的絕對值更小

二、向上取整:math.ceil()

>>> import math

>>>

>>> math.ceil(0.6)

1

>>> math.ceil(1.1)

2

>>> math.ceil(3.0)

3

>>> math.ceil(-0.3)

>>> math.ceil(-5.1)

-5

總結:math.ceil()嚴格遵循向上取整,所有小數都是向着數值更大的方向取整,不論正負數都如此

三、向下取整:math.floor() , “//”

>>> import math

>

>>> math.floor(0.5)

>>> math.floor(1.2)

1

>>> math.floor(-0.9)

-1

>>> math.floor(-3.0)

-3

>>> math.floor(-3.1)

-4

總結:math.floor()嚴格遵循向下取整,所有小數都是向着數值更小的方向取整,不論正負數都如此

再看看python的取整“//“,同樣是向下取整,記住啊:

>>> 5//3

1

>>> 1//5

>>> 8//4

2

>>> -6//5

-2

>>> -8//9

-1

>>> -8//2

-4

四、四舍五入 round(x,[.n])

>>> round(1.1)

1

>>> round(4.5)

4

>>> round(4.51)

5

>>> round(-1.3)

-1

>>> round(-4.5)

-4

>>> round(-4.51)

-5

>>> round(1.248,2)

1.25

>>> round(1.241,2)

1.24

>>> round(-1.248,1)

-1.2

>>> round(1.25,1)

1.2

>>>

這裡注意:round(4.5)的結果是4,round(4.51)的結果才是5,這裡要看5後面的數字,隻有大于5時才進1,恰好等于5時還是舍去的。這與我們字面上了解的”五入“有所出入(Python 3.7.4)。

五、分别取整數和小數部分 math.modf()

>>> math.modf(100.123)

(0.12300000000000466, 100.0)

>>> math.modf(-100.123)

(-0.12300000000000466, -100.0)

>>>

math.modf()函數得到一個(x,y)的元組,x為小數部分,y為整數部分(這裡xy均為float浮點數)

注意:結果是”小數+整數“,而非”整數+小數“。

六、%求模

python運算符%取模 – 傳回除法的餘數

>>> 5%2

1

>>> 0.5%2

0.5

>>> 5.3%2

1.2999999999999998“`

正數很好了解,這裡傳回的餘數時一個無線接近結果的近似值。

“`python

>>> -2.5%8

5.5

>>> -3.2%2

0.7999999999999998

>>> 5%-2

-1

>>> 5%(-3)

-1

>>> 5.2%-2

-0.7999999999999998

>>> -8%-3

-2

>>> -2%-8

-2

>>> -2%-9

-2

懵了,為什麼不是:-2.5和-1.2,而是:5.5和0.8?

求模運算規則是由除法規則定的:

模=被除數-除數×商

這裡的”商”的值其本質是由python的整除//采取的向下取整算法決定的。是以,整理下公式就是這樣的:

模=被除數-除數×(被除數//除數)

釋出者:全棧程式員棧長,轉載請注明出處:https://javaforall.cn/128438.html原文連結:https://javaforall.cn