2013-12-23 201 views
1

在Python中,我想分兩個數字,如果答案不是整數,我希望數字四捨五入到上面的數字。
例如100/30不給33.3但給任何人都可以建議如何做到這一點?謝謝。Python3.3四捨五入

+0

什麼約'-100/33'? '-3'還是'-4'? –

+0

「10/9.9999」呢? '1'還是'2'? –

回答

2

您可以使用Python有數學庫的小區功能,但你也可以看看爲什麼在邏輯上

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) 
+1

謝謝你已完美的工作,我現在也理解邏輯。 – user3130576

+0

@ user3130576你可能想檢查的一個額外的情況是,b不能是0,我忘了這麼做,讓我再次更新它:) – JoeC

7

可以使用math.ceil()功能:

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

請注意,如果問題是關於Python 2的,那麼您需要輸出結果:'int(math.ceil(float(100)/ 33))'。這是從2更改爲3. –