After accept answer
In C, since C99, the result of % is well defined even with negative operands. See below.
In C, % operator is named the "remainder" in C and not "modulus".
To perform a Euclidean division & remainder without incurring truncation, range, double conversion problems **:
void Euclidean_divide_remainder(int a, int b, int *q, int *r) {
*q = a / b;
*r = a % b;
if (a < 0 && *r != 0) {
if (b < 0) { (*q)++; *r -= b; }
else { (*q)--; *r += b; }
}
}
void rtest(int a, int b) {
int eq, er;
Euclidean_divide_remainder(a, b, &eq, &er);
printf("f(%2d,%2d) / %2d %% %2d E/ %2d E%% %2d\n",
a, b, a / b, a % b, eq, er);
}
void rtest4(int a, int b) {
rtest(a, b);
rtest(a, -b);
rtest(-a, b);
rtest(-a, -b);
printf("\n");
}
int main(void) {
rtest4(7, 3);
return 0;
}
f( 7, 3) / 2 % 1 E/ 2 E% 1
f( 7,-3) / -2 % 1 E/ -2 E% 1
f(-7, 3) / -2 % -1 E/ -3 E% 2
f(-7,-3) / 2 % -1 E/ 3 E% 2
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. In both operations, if the value of the second operand is zero, the behavior is undefined. C11dr §6.5.5 5
When integers are divided, the result of the / operator is the algebraic quotient with any
fractional part discarded. (This is often called ‘‘truncation toward zero’’.) If the quotient a/b is representable, the expression (a/b)*b + a%b shall equal a; otherwise, the behavior of both a/b and a%b is undefined. C11dr §6.5.5 6
** Exceptions:
The result of a%0 is undefined.
For 2's complement, INT_MIN % -1 and INT_MIN E% -1 (which mathematically should be 0) are problems. This is caused by INT_MIN / -1 (which mathematically should be INT_MAX + 1) is a problem as the answer does not fit in the int range..
scanf()for the answer generated by the%operator.a%bis "the wrong answer for a modulus operation". IMO: This borders on either side of a duplicated post.