在Python中,我想将两个数字相除,如果答案不是整数,我希望将该数字向上舍入到上面的数字。
例如,100/30不是给33.3而是给4。有没有人能建议怎么做?谢谢。
发布于 2013-12-24 04:07:01
您可以在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)发布于 2013-12-24 03:59:30
您可以使用math.ceil()函数:
>>> import math
>>> math.ceil(100/33)
4https://stackoverflow.com/questions/20750297
复制相似问题