簡體   English   中英

Python3.3舍入

[英]Python3.3 rounding up

在Python中,我想將兩個數字相除,如果答案不是整數,則希望將數字四舍五入為上述數字。
例如100/30不給33.3,而是給4。有人可以建議如何做嗎? 謝謝。

您可以使用math.ceil()函數:

>>> import math
>>> math.ceil(100/33)
4

您可以使用python具有的數學庫中的ceil函數,但也可以從邏輯上看一下原因

a = int(100/3) # this will round down to 3
b = 100/3 # b = 33.333333333333336, a and b are not equal

so we can generalize into the following

def ceil(a, b):
    if (b == 0):
        raise Exception("Division By Zero Error!!") # throw an division by zero error
    if int(a/b) != a/b:
        return int(a/b) + 1
    return int(a/b)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM