Android: which operator for modulo (% does not work with negative numbers)

If i try

int a=(-2)%6

I get -2 instead of 4 .

Why does he behave this way with negative numbers?

+5
source share
2 answers

% performs a remainder operation in Java.

To get the correct module, you can use the remainder in the function:

This is the shortest use of the ternary operator to fix the sign:

private int mod(int x, int y)
{
    int result = x % y;
    return result < 0? result + y : result;
}

For those who don't like the ternary operator, this is equivalent to:

private int mod(int x, int y)
{
    int result = x % y;
    if (result < 0)
        result += y;
    return result;
}
+24
source

Because if you divide -2 by 6, you get -2 as the remainder. % will give the remainder as shown below:

int remainder = 7 % 3;  // will give 1
int remainder2 = 6 % 2; // will give 0

Get the module:

    // gives m ( mod n )
public int modulo( int m, int n ){
    int mod =  m % n ;
    return ( mod < 0 ) ? mod + n : mod;
}
+8
source

All Articles