java整數(shù)除法看似簡(jiǎn)單,但是仔細(xì)考慮就會(huì)發(fā)現(xiàn)一些細(xì)節(jié)并不是顯而易見的。例如,-9/4結(jié)果是-2還是-3?
查閱了《java編程思想》(第四版 機(jī)械工業(yè)出版社 陳昊鵬譯 41頁):
整數(shù)除法會(huì)直接去掉結(jié)果的小數(shù)位,而不是四舍五入地圓整結(jié)果。
以及《Java 核心技術(shù) 卷I》(第十版 機(jī)械工業(yè)出版社 周立新等譯 38頁):
當(dāng)與/運(yùn)算的兩個(gè)操作數(shù)都是整數(shù)時(shí),表示整數(shù)除法
都沒有明確的說明具體的預(yù)期結(jié)果。因此,從網(wǎng)上查閱了java的specifiction15.17.2. Division Operator /
The binary
/operator performs division, producing the quotient of its operands. The left-hand operand is the dividend and the right-hand operand is the divisor.
二元操作符 / 對(duì)操作數(shù)進(jìn)行除法運(yùn)算,得到二者之商。左邊的操作符是被除數(shù),右邊的操作數(shù)是除數(shù)。
Integer division rounds toward
0. That is, the quotient produced for operands n and d that are integers after binary numeric promotion (§5.6.2) is an integer value q whose magnitude is as large as possible while satisfying |d ? q| ≤ |n|. Moreover, q is positive when |n| ≥ |d| and n and d have the same sign, but q is negative when |n| ≥ |d| and n and d have opposite signs.
整數(shù)除法在 0附近取整。也就是說對(duì)于整數(shù) n 和 d,他們的商是滿足以下條件的具有最大magnitude(我理解是絕對(duì)值)的整數(shù)
|d ? q| ≤ |n|
進(jìn)一步說,當(dāng) |n| ≥ |d| 并且 n 和 d 的符號(hào)相同的時(shí)候,q 為正;當(dāng) |n| ≥ |d| 并且 n 和 d 的符號(hào)不同的時(shí)候,q 為負(fù)。
這里還有隱含一層的意思,即當(dāng) |n| < |d| 的時(shí)候,q 為 0。
There is one special case that does not satisfy this rule: if the dividend is the negative integer of largest possible magnitude for its type, and the divisor is
-1, then integer overflow occurs and the result is equal to the dividend. Despite the overflow, no exception is thrown in this case. On the other hand, if the value of the divisor in an integer division is0, then anArithmeticExceptionis thrown.
有一個(gè)特例不滿足這一法則:如果被除數(shù)為負(fù),且其絕對(duì)值為所有同類型負(fù)數(shù)中的最大值,在除數(shù)為 -1 的情況下,如果按照上述規(guī)則,會(huì)發(fā)生溢出,因此此時(shí)輸出和被除數(shù)相同。盡管發(fā)生了溢出,也不會(huì)有異常拋出。另一方面,如果除數(shù)為 0, 就會(huì)拋出 ArithmeticException 。
代碼演示:
private static void test1(){
System.out.println(9/4);
System.out.println(9/-4);
System.out.println(-9/4);
System.out.println(-9/-4);
System.out.println(4/9);
System.out.println(-4/9);
System.out.println(4/-9);
System.out.println(-4/-9);
System.out.println(Integer.MIN_VALUE/-1);
}
輸出
2
-2
-2
2
0
0
0
0
-2147483648