【发布时间】:2016-11-26 17:20:51
【问题描述】:
整数除法没有按预期四舍五入让我感到意外。
简单代码:
public class HelloMath {
public static void main(String[] args) {
for (int s=1; s< 20; s++)
{
int div = 1<<s;
int res = (int) ((float)-8/ s);
System.out.printf("Bit %d, result %d\n", s, res);
}
}
}
即使使用显式 (float) 强制转换,输出也是:
Bit 1, result -8
Bit 2, result -4
Bit 3, result -2
Bit 4, result -2
Bit 5, result -1
Bit 6, result -1
Bit 7, result -1
Bit 8, result -1
Bit 9, result 0
Bit 10, result 0
Bit 11, result 0
Bit 12, result 0
Bit 13, result 0
Bit 14, result 0
Bit 15, result 0
Bit 16, result 0
Bit 17, result 0
Bit 18, result 0
Bit 19, result 0
我一直期待-1。
发生这种情况的真实代码是这样的:
public static int fluidTo8th(int fluid)
{
if (0 == fluid)
return 0; // Technically, this isn't needed :-).
int wholePart = (fluid-1) * 8 / RealisticFluids.MAX_FLUID; // -1 gets rounding correct;
// consider fluid of exactly 1/8th.
return 1+wholePart;
}
RealisticFluids.MAX_FLUID 的值为 (1
我希望整数数学可以将所有分数向下舍入。但这并没有发生——我到处都是一个错误,因为 5.999 最终变成了 6 而不是 5。
- 这种行为记录在哪里?
- 什么是最简单的解决方法来获得我预期的四舍五入?
【问题讨论】:
-
如果您实际除以
div,而不是除以s,结果可能会有所不同。我的意思是,你确实创建了div,我想是有原因的。 -
当
s = 1时,-8 除以s为-8,-8 除以div(1s = 9时,-8除以s为0(从-0.8888889向下取整),-8除以div(1
标签: java integer rounding division truncation