Java 如何四舍五入到下一个整数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19689128/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 19:24:28  来源:igfitidea点击:

How to round up to the next integer?

javamath

提问by membersound

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

Is Math.ceil()the right way to go?

Math.ceil()走的路吗?

采纳答案by kviiri

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

不,Math.ceil()不会单独工作,因为问题发生得更早。ab都是整数,所以将它们相除等于一个整数,它是除法实际结果的下限。对于a = 3b = 2,结果是1。一个的上限也是一个 - 因此你不会得到想要的结果。

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.ceilto round it up. This code should work:

你必须先修复你的部门。通过将操作数之一转换为浮点数,您可以根据需要获得非整数结果。然后你可以用Math.ceil它来四舍五入。此代码应该工作:

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

回答by Henry

You can use this expression

你可以用这个表达

(a+b-1)/b

回答by njzk2

a division between 2 integers (also known as integer division) yields the remaining of the division.

2 个整数(也称为integer division)之间的除法产生除法的剩余部分。

3/2 = 1

To use ceil, you need to make a division that is not integer.:

要使用 ceil,你需要做一个非整数的除法:

You can either declare your values as doubles (3.0or 3d) or cast them before dividing:

您可以将您的值声明为 doubles ( 3.0or 3d) 或在除法之前强制转换它们:

((double) 3) / ((double) 2) = 1.5

This double value can be used in ceil.

这个双精度值可以在 ceil 中使用。

Math.ceil(3.0 / 2.0) = 2.0;

回答by Bacteria

The return type of Math.ceil method is doublewhere is, the return type of Math.round is int. so if you want that, the result will be in integer then you should use Math.round method, or else Math.ceil method is fine.

Math.ceil 方法的返回类型是double,其中 Math.round 的返回类型是int。所以如果你想要,结果将是整数,那么你应该使用 Math.round 方法,否则 Math.ceil 方法就可以了。

float x = 1654.9874f;     
System.out.println("Math.round(" + x + ")=" + Math.round(x));   
System.out.println("Math.ceil(" + x + ")=" + Math.ceil(x));

Out put

输出

Math.round(1654.9874)=1655

Math.ceil(1654.9874)=1655.0