How to perform ceiling-division in integer arithme

2020-04-02 09:59发布

It's basically returning the boxes_needed. 1 box can contain 10 items. So if the items typed by the user is 102 then the code should return 11 boxes.

Is there a way to divide that rounds upwards if there is a non-zero remainder?

4条回答
在下西门庆
2楼-- · 2020-04-02 10:04

Negate before and after?

>>> -(-102 // 10)
11
查看更多
SAY GOODBYE
3楼-- · 2020-04-02 10:09

For your use case, use integer arithmetic. There is a simple technique for converting integer floor division into ceiling division:

items = 102
boxsize = 10
num_boxes = (items + boxsize - 1) // boxsize

Alternatively, use negation to convert floor division to ceiling division:

num_boxes = -(items // -boxsize)
查看更多
仙女界的扛把子
4楼-- · 2020-04-02 10:19

You can try :

import math
math.ceil( x )
查看更多
Explosion°爆炸
5楼-- · 2020-04-02 10:27
from math import ceil

print(ceil(10.3))

11
查看更多
登录 后发表回答