如何在整数算术中执行天花板除法? [英] How to perform ceiling-division in integer arithmetic?

查看:75
本文介绍了如何在整数算术中执行天花板除法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

它基本上返回了 box_needed.1 盒可装 10 件物品.因此,如果用户键入的项目是 102,则代码应返回 11 个框.

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?

推荐答案

对于您的用例,请使用整数算法.有一个简单的技术可以将整数地板除法转换为天花板除法:

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)

这篇关于如何在整数算术中执行天花板除法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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