如何在 Java 中向上和向下舍入数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35785378/
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
How to round up and down numbers in Java
提问by Tarikh Chouhan
Im trying to make my program evaluate a expression from left to right ignoring order of operations.
我试图让我的程序从左到右评估表达式,而忽略操作顺序。
E.g. 5/3+2*3 = 12
例如 5/3+2*3 = 12
Division should round up/down to the nearest integer. In this example, 5/3 should equate to 2 since 5/3 = 1.666 which rounds up to 2.
除法应向上/向下舍入到最接近的整数。在此示例中,5/3 应等于 2,因为 5/3 = 1.666,四舍五入为 2。
I have made a function which does computes the expression and it works perfectly up until the point the expression involves division. It doesn't round the number properly. This is how it computes the divion in my code:
我制作了一个计算表达式的函数,它可以完美运行,直到表达式涉及除法为止。它没有正确舍入数字。这是它在我的代码中计算divion的方式:
if (runningTotal % numbers.get(i + 1) >= 5) {
runningTotal = (int) Math.ceil(runningTotal / numbers.get(i + 1));
} else {
runningTotal = (int) Math.floor(runningTotal / numbers.get(i + 1));
}
runningTotal is an int and numbers is an arraylist containing integers. Is there something wrong with my casting?
runningTotal 是一个 int 而 numbers 是一个包含整数的数组列表。我的选角有问题吗?
Thanks for helping.
谢谢你的帮助。
EDIT = Figured it out myself. Forgot all about Math.round()....
编辑 = 自己想出来的。忘记了 Math.round()....
回答by
Math.round()rounds to the next higher number (in double form) if the fractional part is >= 5, i.e., 7.5, 7.6... will become 8.0. Math.ceil()rounds to the next higher integer number irrespective of the factional part, i.e., 7.4 will become 8.0. And Math.floor()is the opposite of ceil(): rounds to the previous integer irrespective of the fractional part, i.e., 7.8 will become 7.0. Math.rint()is just like Math.round(), but it returns the value in int form. So you might wanna do this:
如果小数部分 >= 5,即 7.5、7.6... 将变为 8.0,Math.round()将舍入到下一个更高的数字(以双精度形式)。Math.ceil() 舍入到下一个更高的整数而不考虑派系部分,即 7.4 将变为 8.0。而Math.floor()则与 ceil() 相反:四舍五入到前一个整数而不考虑小数部分,即 7.8 将变为 7.0。 Math.rint()与 Math.round() 类似,但它以 int 形式返回值。所以你可能想这样做:
int r= Math.round(5.0/3.0)+2*3;
//or
int r=Math.rint(5.0/3.0)+2*3;
//rint() in preferable if 'r' is int
回答by endorphins
Your problem is that you are doing integer division, which will only produce whole numbers. By the time the ceil or floor methods are called, the result is already truncated. Try casting the ints to floats.
你的问题是你正在做整数除法,它只会产生整数。调用 ceil 或 floor 方法时,结果已被截断。尝试将整数转换为浮点数。
Math.ceil((float)runningTotal / (float)numbers.get(i + 1))
Math.ceil((float)runningTotal / (float)numbers.get(i + 1))