首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python3.3向上舍入

Python3.3向上舍入
EN

Stack Overflow用户
提问于 2013-12-24 03:57:04
回答 2查看 9.6K关注 0票数 3

在Python中,我想将两个数字相除,如果答案不是整数,我希望将该数字向上舍入到上面的数字。

例如,100/30不是给33.3而是给4。有没有人能建议怎么做?谢谢。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-12-24 04:07:01

您可以在python的数学库中使用ceil函数,但也可以从逻辑上了解原因。

代码语言:javascript
复制
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)
票数 4
EN

Stack Overflow用户

发布于 2013-12-24 03:59:30

您可以使用math.ceil()函数:

代码语言:javascript
复制
>>> import math
>>> math.ceil(100/33)
4
票数 12
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20750297

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档