x=-10 % -4;
System.out.println("-10% -4 : "+x); //-2 second row
The output '-2' why in the answer is a negative value?
x=-10 % -4;
System.out.println("-10% -4 : "+x); //-2 second row
The output '-2' why in the answer is a negative value?
% is remainder division. It is the amount left over after the integer division.
x = -10 / -4; // == 2
and
x = -10 % -4; // == -2
The later can be thought of as -10 divided by -4 (which is 2) with a remainder of -2.
It might be easier to see if both answers were not the same absolute value.
x = -10 / -3; // == 3
and
x = -10 % -3; == -1
Unfortunately that is the way the Java modulus operator works with negative numbers. If you want only positive remainder values then do a simple conversion like this:
if(x < 0){
x = x * -1;
}