如何舍入到下一个整数? [英] How to round up to the next integer?

查看:55
本文介绍了如何舍入到下一个整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将两个整数除以一个下一个整数的正确方法是什么?

What is the correct way to round a division of two integers up to the next integer?

int a = 3;
int b = 2;

a / b = ? //should give 2

Math.ceil()是正确的方法吗?

推荐答案

不,Math.ceil() 不会单独工作,因为问题发生得更早. a b 都是整数,因此将它们相除会得出一个整数,该整数是除法实际结果的下限.对于 a = 3 b = 2 ,结果为 1 .一的上限也是一-因此您将无法获得理想的结果.

No, Math.ceil() won't work on its own because the problem occurs earlier. a and b are both integers, so dividing them evaluates to an integer which is the floor of the actual result of the division. For a = 3 and b = 2, the result is 1. The ceiling of one is also one - hence you won't get the desired result.

您必须先确定您的部门.通过将操作数之一转换为浮点数,可以得到所需的非整数结果.然后,您可以使用 Math.ceil 对其进行四舍五入.这段代码应该可以工作:

You must fix your division first. By casting one of the operands to a floating point number, you get a non-integer result as desired. Then you can use Math.ceil to round it up. This code should work:

Math.ceil((double)a / b);

这篇关于如何舍入到下一个整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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