This question already has an answer here:
- Modulo operation with negative numbers 12 answers
A modulo operation a%b returns the remainder for a/b but for negative numbers it does not do so.
#include <stdio.h>
int main(void) {
int n=-4;
printf("%d\n",n%3);
return 0;
}
It should return 2 as 3*(-2)=-6 is just smaller than -4 and a multiple of 3 but the output is -1.
Why is it treating (-a) mod b same as -(a mod b)
As a general rule, the modulo and division should satisfy the equation
b * (a/b) + a%b == a
For positive numbers, it is obvious that this means that a%b must be a positive number. But if a/b is negative, then the result is rounded towards zero.
So take for instance a = -4, b = 3. We know that a/b = -1.3333, which rounded towards zero becomes a/b == -1. From the equation above, we have that b * (-1) + a%b == a. If we insert a and b, we get -3 + a%b == -4, and we see that a%b must be -1.
Your suffering stems from embracing the illusion that % is a "modulo" operator. In truth, it is a remainder operator (C11 §6.5.5):
The result of the
/operator is the quotient from the division of the first operand by the second; the result of the%operator is the remainder
Reject the illusion and accept the truth, and the behavior of the operator will become clear (Ibid.):
If the quotient
a/bis representable, the expression(a/b)*b + a%bshall equala
In your case, a/b is -4/3, which is -1, hence representable. So a%b satisfies:
(a/b)*b + a%b = a
(-1)*3 + a%b = -4
-3 + a%b = -4
a%b = -1
来源:https://stackoverflow.com/questions/30199474/modulo-operation-on-negative-numbers