Python3.3 rounding up

ⅰ亾dé卋堺 提交于 2019-12-22 18:38:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!