V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
kenneth
V2EX  ›  Python

Python除法如何向上取整?

  •  
  •   kenneth · 2012-12-30 11:23:53 +08:00 · 21542 次点击
    这是一个创建于 4143 天前的主题,其中的信息可能已经有所发展或是发生改变。
    求思路。
    11 条回复    1970-01-01 08:00:00 +08:00
    clowwindy
        1
    clowwindy  
       2012-12-30 11:28:10 +08:00
    >>> round(2.5)
    3.0

    指这个?
    clowwindy
        2
    clowwindy  
       2012-12-30 11:29:22 +08:00
    >>> math.ceil(2.1)
    3.0
    kenneth
        3
    kenneth  
    OP
       2012-12-30 11:33:45 +08:00
    @clowwindy 我是说python除法的向上取整,你的是向上取整,但是不是python除法。
    darcy
        4
    darcy  
       2012-12-30 11:44:37 +08:00 via iPhone   ❤️ 6
    UP(A/B) = int((A+B-1)/B)
    楼主要的这个?
    funagi
        5
    funagi  
       2012-12-30 11:47:47 +08:00
    reusFork
        6
    reusFork  
       2012-12-30 15:16:12 +08:00 via Android
    math.ceil(10 / 3.0)
    sNullp
        7
    sNullp  
       2012-12-30 15:26:33 +08:00
    @reusFork 楼主两个数字都是整型。4楼是正解。
    reusFork
        8
    reusFork  
       2012-12-30 15:36:20 +08:00
    @sNullp 这个公式确实方便,我之前都是用math.ceil(A / float(B))
    yegle
        9
    yegle  
       2012-12-31 17:08:17 +08:00 via iPad
    看了半天才明白…

    from __future__ import division
    result = math.ceil(3/2)

    最简单明了了
    reloop
        10
    reloop  
       2013-12-06 16:35:30 +08:00
    @darcy
    @sNullp
    @reusFork
    请问为什么 UP(A/B) = int( (A+B-1)/B ) 可以向上取整? 计算过程是怎样的?
    sNullp
        11
    sNullp  
       2013-12-06 21:16:16 +08:00
    计算过程就是 A 加 B 减 1 除 B。。
    你拿纸算一下 A+B-1 的范围就知道了
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2321 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 06:25 · PVG 14:25 · LAX 23:25 · JFK 02:25
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.