How to perform ceiling-division in integer arithmetic? [duplicate]

て烟熏妆下的殇ゞ 提交于 2019-12-04 03:19:22

问题


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?


回答1:


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)



回答2:


Negate before and after?

>>> -(-102 // 10)
11



回答3:


from math import ceil

print(ceil(10.3))

11



回答4:


You can try :

import math
math.ceil( x )


来源:https://stackoverflow.com/questions/33299093/how-to-perform-ceiling-division-in-integer-arithmetic

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