日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網(wǎng)站首頁 編程語言 正文

python如何實現(xiàn)向上取整_python

作者:普通網(wǎng)友 ? 更新時間: 2023-03-28 編程語言

python如何取整

數(shù)據(jù)處理是編程中不可避免的,很多時候都需要根據(jù)需求把獲取到的數(shù)據(jù)進行處理,取整則是最基本的數(shù)據(jù)處理。

取整的方式則包括向下取整、四舍五入、向上取整等等。

1、向下取整

向下取整直接用內建的 int() 函數(shù)即可:

>>> a = 3.75
>>> int(a)
3

2、四舍五入

對數(shù)字進行四舍五入用 round() 函數(shù):

>>> round(3.25); round(4.85)
3.0
5.0

3、向上取整

向上取整需要用到 math 模塊中的 ceil() 方法:

>>> import math
>>> math.ceil(3.25)
4.0
>>> math.ceil(3.75)
4.0
>>> math.ceil(4.85)
5.0

4、分別取整數(shù)部分和小數(shù)部分

有時候我們可能需要分別獲取整數(shù)部分和小數(shù)部分,這時可以用 math 模塊中的 modf() 方法,該方法返回一個包含小數(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)

有人可能會對最后一個輸出結果感到詫異,按理說它應該返回 (0.2, 4.0) 才對。

這里涉及到了另一個問題,即浮點數(shù)在計算機中的表示,在計算機中是無法精確的表示小數(shù)的,至少目前的計算機做不到這一點。

上例中最后的輸出結果只是 0.2 在計算中的近似表示。

python中的取整問題

雖然取整是各種語言中最基礎的操作, 可是往往多了一個1或者少了一個1會導致巨大的災難,所以我覺得還是很有必要寫一下的。

python中的取整操作有://, round, int, ceil, floor, 其他語言也有類似的函數(shù)來進行取整。

先看一段代碼

import math

def test_round(a, b):
? ? print('-------------------------------------')
? ? print(f'{a}/{b}=', a/b)
? ? print(f'{a}//{b}=', a//b)
? ? print(f'round({a}/{b})=', round(a/b))
? ? print(f'int({a}/{b})=', int(a/b))
? ? print(f'ceil({a}/{b})=', math.ceil(a/b))
? ? print(f'floor({a}/{b})=', math.floor(a/b))

test_round(3, 2)
test_round(-3, 2)

打印結果:

-------------------------------------
3/2= 1.5
3//2= 1
round(3/2)= 2
int(3/2)= 1
ceil(3/2)= 2
floor(3/2)= 1
-------------------------------------
-3/2= -1.5
-3//2= -2
round(-3/2)= -2
int(-3/2)= -1
ceil(-3/2)= -1
floor(-3/2)= -2

可以看出, //操作結果和floor是一樣的。

總的來說, ceil:坐標軸上向上取整, floor:向下取整, int:向中(0)取整(直接去掉浮點位)。

而round則是四舍五入(不考慮符號)

總結

原文鏈接:https://blog.csdn.net/m0_51713294/article/details/110632272

欄目分類
最近更新