Negative Remainder Values in the Modulo Operation
When performing modulo operations, where one operand is negative, unexpected results may arise. This article explores why operations like (-7 % 3) and (7 % -3) produce seemingly inconsistent results of -1 and 1, respectively.
According to the ISO14882:2011 standard, the modulo operator (%) provides the remainder after dividing the first operand by the second. While dividing integers generally involves discarding the fractional part, the modulo operator also considers the signs of the operands.
In the case of (-7 % 3), the result of -7 / 3 is -2. Multiplying -2 by 3 gives -6, indicating that the remainder is -1. Therefore, (-7 % 3) = -1.
Similarly, for (7 % -3), 7 / -3 yields -2. Multiplying -2 by -3 results in 6, making the remainder 1. Thus, (7 % -3) = 1.
It's important to note that the modulo operation exhibits implementation-defined behavior when the result is negative. While some implementations may preserve the negative sign, the ISO14882:2011 standard no longer enforces this. Therefore, the negative sign in (-7 % 3) is system-dependent.
The above is the detailed content of Why Does the Modulo Operator (%) Produce Different Results with Negative Numbers?. For more information, please follow other related articles on the PHP Chinese website!