c99 standard says that result of modulo operation has same sign as first operand. So -9 % 7 = -2
and 9 % -7 = 2
.
I read in one book that c89 standard depends on implementation. So -9 % 7
could yield -2
or 5
??? How remainder of -9 / 7
could be 5
?
Remainder (%) The remainder operator ( % ) returns the remainder left over when one operand is divided by a second operand.
The modulus operator is added in the arithmetic operators in C, and it works between two available operands. It divides the given numerator by the denominator to find a result. In simpler words, it produces a remainder for the integer division. Thus, the remainder is also always an integer number only.
The // (remainder) operator returns the remainder from integer division and is defined as being the residue of the dividend after the operation of calculating integer division as previously described. The sign of the remainder, if nonzero, is the same as that of the original dividend.
Modulo Operator (%) in C/C++ with Examples The modulo division operator produces the remainder of an integer division.
%
operator is defined as:
a == (a / b * b) + a % b
so
a % b = a - (a / b * b)
% as a remainder operator
If /
rounds towards 0
(like C99):
-9 % 7 == -2
you have -9 / 7 == -1
so the %
is -2
because
-9 % 7 == -9 - (-9 / 7 * 7) + 9 == -9 + 7 == -2
% as a modulo operator
If /
rounds towards minus infinity:
-9 % 7 == 5
you have -9 / 7 == -2
so the %
is 5
-9 % 7 == -9 - (-9 / 7 * 7) + 9 == -9 + 14 == 5
Consider two numbers a
and b
.
The quotient q=a/b
and remainder r=a%b
satisfy the equation a == q*b + r
.
An (hypothetical) implementation of C89 in which -9 % 7 produces 5 is an implementation in which -9 / 7 is computed as -2.
The mathematical (Euclidian) division constrains r
to be positive and smaller than b
. C99 constrains it to be of the same sign as a
and strictly between -b
and b
.
It is all only a matter of convention.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With