G
gk
Int a = -5; Int b = -2;
System.out.println(a % b); // -1
how this is working ?
System.out.println(a % b); // -1
how this is working ?
(How does this work?)Int a = -5; Int b = -2;
System.out.println(a % b); // -1
how this is working ?
gk said:Int a = -5; Int b = -2;
System.out.println(a % b); // -1
how this is working ?
Lars said:gk skrev:
(How does this work?)
According to the definition of the % operator -1 is the rest after
taking out a multiple (-4) of -2 from -5.
Patricia said:For integer operands, % is designed to maintain the identity:
(a/b)*b+(a%b) is equal to a.
Java integer division rounds towards zero, so -5/-2 is 2.
( (-5)/(-2) ) * (-2) + (-1) is -5.
A nitpick question: Is the division ( (8)/(3) ) also 2 in Java?
If so, why is this be called "rounding"?
Richard said:A nitpick question: Is the division ( (8)/(3) ) also 2 in Java?
If so, why is this be called "rounding"?
Patricia said:Strictly speaking, there is no "mod" operator in Java. % is defined to
be "remainder". It is the same as modulo for positive operands.
For integer operands, % is designed to maintain the identity:
(a/b)*b+(a%b) is equal to a.
Java integer division rounds towards zero, so -5/-2 is 2.
( (-5)/(-2) ) * (-2) + (-1) is -5.
See the JLS,
http://java.sun.com/docs/books/jls/second_edition/html/expressions.doc.html#239829
Patricia
Illuminating post - thanks.Patricia Shanahan said:gk wrote:
> Int a = -5; Int b = -2;
> System.out.println(a % b); // -1
>
> how this is working ?
>
Strictly speaking, there is no "mod" operator in Java. % is defined to
be "remainder". It is the same as modulo for positive operands.
For integer operands, % is designed to maintain the identity:
(a/b)*b+(a%b) is equal to a.
Java integer division rounds towards zero, so -5/-2 is 2.
( (-5)/(-2) ) * (-2) + (-1) is -5.
See the JLS,
Patricia
Want to reply to this thread or ask your own question?
You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.