[英]Python3.3 rounding up
In Python I would like to divide two numbers and if the answer is not an integer I want the number to be rounded up to the number above. 在Python中,我想将两个数字相除,如果答案不是整数,则希望将数字四舍五入为上述数字。
For example 100/30 not to give 33.3 but to give 4. Can anyone suggest how to do this? 例如100/30不给33.3,而是给4。有人可以建议如何做吗? Thanks.
谢谢。
You can use the math.ceil()
function: 您可以使用
math.ceil()
函数:
>>> import math
>>> math.ceil(100/33)
4
you can use the ceil function in math library that python has, but also you can take a look why in a logical sense 您可以使用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.