java整數(shù)取余是建立在java整數(shù)除法的基礎(chǔ)上的比原,java整數(shù)除法可以參考我的上一篇文章java 整數(shù)除法巴柿。
這里我們?nèi)匀粎⒖糺ava 的 Specification jls-15.17.3:
The remainder operation for operands that are integers after binary numeric promotion (§5.6.2) produces a result value such that
(a/b)*b+(a%b)
is equal toa
.
a,b兩數(shù)之余滿足:
(a/b)*b+(a%b) = a
This identity holds even in the special case that the dividend is the negative integer of largest possible magnitude for its type and the divisor is
-1
(the remainder is0
).
在被除數(shù)為該類型負數(shù)中絕對值最大的一個且除數(shù)為 -1
時漠秋,這一法則依然成立烹看,此時百宇,余數(shù)為 0
豁延。
It follows from this rule that the result of the remainder operation can be negative only if the dividend is negative, and can be positive only if the dividend is positive. Moreover, the magnitude of the result is always less than the magnitude of the divisor.
按照這一法則,只有在被除數(shù)為負的情況下腊状,余數(shù)才能為負诱咏;只有在被除數(shù)為正的情況下,余數(shù)才能為正缴挖。而且袋狞,余數(shù)的絕對值永遠小于除數(shù)的絕對值。
代碼演示
private static void test2(){
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);
}
輸出
1
1
-1
-1
4
-4
4
-4
0