如何在不使用“舍入函数”或“if 和 else 语句”的情况下将数字舍入到 Java 中最接近的整数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18690038/
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 do you round a number to the closest integer in java without using the "round function" or "if and else statements"?
提问by CougarTown
I have to round a number to the nearest integer. So 4.3 would be rounded to 4 and 4.7 would be rounded to 5. Numbers that have decimals in the middle like 4.5 would be rounded to 5 as well. I have to do this rounding without using and "Math." functions or "if and else statements".
我必须将一个数字四舍五入到最接近的整数。因此,4.3 将四舍五入为 4,4.7 将四舍五入为 5。中间有小数的数字(如 4.5)也将四舍五入为 5。我必须在不使用和“数学”的情况下进行四舍五入。函数或“if 和 else 语句”。
采纳答案by tbodt
The answer is pretty simple. Add 0.5 to the number and then cast it to an int. Like this:
答案很简单。将 0.5 添加到数字上,然后将其转换为 int。像这样:
int rounded = (int) (unrounded + 0.5);
This works because if the decimal part is less than 0.5, the integer part stays the same, and truncation gives the right result. If the decimal part is more that 0.5, the integer part increments, and again truncation gives what we want.
这是有效的,因为如果小数部分小于 0.5,整数部分保持不变,截断给出正确的结果。如果小数部分大于 0.5,则整数部分递增,再次截断给出我们想要的。