问题
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.
For example 100/30 not to give 33.3 but to give 4.
Can anyone suggest how to do this? Thanks.
回答1:
you can use the ceil function in math library that python has, but also you can take a look why in a logical sense
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)
回答2:
You can use the math.ceil() function:
>>> import math
>>> math.ceil(100/33)
4
来源:https://stackoverflow.com/questions/20750297/python3-3-rounding-up