3 回答

TA貢獻1802條經(jīng)驗 獲得超10個贊
JDK 6中的源代碼:
public static long round(double a) {
return (long)Math.floor(a + 0.5d);
}
JDK 7中的源代碼:
public static long round(double a) {
if (a != 0x1.fffffffffffffp-2) {
// a is not the greatest double value less than 0.5
return (long)Math.floor(a + 0.5d);
} else {
return 0;
}
}
當值為0.49999999999999994d時,在JDK 6中,它將調(diào)用floor,因此返回1,但在JDK 7中,if條件是檢查該數(shù)字是否為小于0.5的最大double值。由于在這種情況下,該數(shù)字不是小于0.5的最大double值,因此該else塊返回0。
您可以嘗試0.49999999999999999d,它將返回1,但不會返回0,因為這是小于0.5的最大double值。

TA貢獻1796條經(jīng)驗 獲得超4個贊
我在32位的JDK 1.6上具有相同的功能,但是在Java 7 64位的上,對于0.49999999999999994則具有0,其四舍五入為0,并且不打印最后一行。這似乎是VM的問題,但是,使用浮點運算,您應(yīng)該期望在各種環(huán)境(CPU,32位或64位模式)下結(jié)果會有所不同。
并且,當使用round或求逆矩陣等時,這些位會產(chǎn)生很大的不同。
x64輸出:
10.5 rounded is 11
10.499999999999998 rounded is 10
9.5 rounded is 10
9.499999999999998 rounded is 9
8.5 rounded is 9
8.499999999999998 rounded is 8
7.5 rounded is 8
7.499999999999999 rounded is 7
6.5 rounded is 7
6.499999999999999 rounded is 6
5.5 rounded is 6
5.499999999999999 rounded is 5
4.5 rounded is 5
4.499999999999999 rounded is 4
3.5 rounded is 4
3.4999999999999996 rounded is 3
2.5 rounded is 3
2.4999999999999996 rounded is 2
1.5 rounded is 2
1.4999999999999998 rounded is 1
0.5 rounded is 1
0.49999999999999994 rounded is 0
添加回答
舉報