Python3.3 四舍五入 [英] Python3.3 rounding up

查看:38
本文介绍了Python3.3 四舍五入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Python 中,我想将两个数字相除,如果答案不是整数,我希望将数字四舍五入为上面的数字.
例如 100/30 不是给出 33.3,而是给出 4.谁能建议如何做到这一点?谢谢.

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.

推荐答案

你可以使用python自带的数学库中的ceil函数,也可以从逻辑上看看为什么

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)

这篇关于Python3.3 四舍五入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆