java 整数取余

java整数取余是建立在java整数除法的基础上的,java整数除法可以参考我的上一篇文章java 整数除法。

这里我们仍然参考java 的 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 to a.

a,b两数之余满足:

 (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 is 0).

在被除数为该类型负数中绝对值最大的一个且除数为 -1 时,这一法则依然成立,此时,余数为 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.

按照这一法则,只有在被除数为负的情况下,余数才能为负;只有在被除数为正的情况下,余数才能为正。而且,余数的绝对值永远小于除数的绝对值。

代码演示

    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

你可能感兴趣的:(java 整数取余)