问题
When I calculate int i = -1 % 2
I get -1
in Java. In Python, I get 1
as the result of -1 % 2
.
What do I have to do to get the same behavior in Java with the modulo function?
回答1:
The problem here is that in Python the % operator returns the modulus and in Java it returns the remainder. These functions give the same values for positive arguments, but the modulus always returns positive results for negative input, whereas the remainder may give negative results. There's some more information about it in this question.
You can find the positive value by doing this:
int i = (((-1 % 2) + 2) % 2)
or this:
int i = -1 % 2;
if (i<0) i += 2;
(obviously -1 or 2 can be whatever you want the numerator or denominator to be)
回答2:
Since Java 8 you can use the Math.floorMod() method:
Math.floorMod(-1, 2); //== 1
Note: If the modulo-value (here 2
) is negative, all output values will be negative too. :)
Source: https://stackoverflow.com/a/25830153/2311557
回答3:
If you need n % m
then:
int i = (n < 0) ? (m - (abs(n) % m) ) %m : (n % m);
mathematical explanation:
n = -1 * abs(n)
-> n % m = (-1 * abs(n) ) % m
-> (-1 * (abs(n) % m) ) % m
-> m - (abs(n) % m))
回答4:
if b > 0:
int mod = (mod = a % b) < 0 ? a + b : a;
Doesn't use the %
operator twice.
回答5:
If the modulus is a power of 2 then you can use a bitmask:
int i = -1 & ~-2; // -1 MOD 2 is 1
By comparison the Pascal language provides two operators; REM takes the sign of the numerator (x REM y
is x - (x DIV y) * y
where x DIV y
is TRUNC(x / y)
) and MOD requires a positive denominator and returns a positive result.
来源:https://stackoverflow.com/questions/5385024/mod-in-java-produces-negative-numbers