繁体   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