Home >Backend Development >C++ >Why Does the Modulo Operator Produce Negative Results with Negative Numbers?
Modulo Operator Results in Negative Values: A Mathematical Explanation
The modulo operator %, when applied to negative numbers, can produce different results depending on the implementation. This can be puzzling, but understanding the mathematical definition of the modulo operator can shed light on this behavior.
According to ISO14882:2011(e) 5.6-4, the modulo operator returns the remainder of the division of the first expression by the second. If the second operand is zero, the behavior is undefined. For integral operands, the quotient is the algebraic quotient with any fractional part discarded.
To illustrate this, consider the following examples:
std::cout << (-7 % 3) << std::endl; // -1 std::cout << (7 % -3) << std::endl; // 1
(-7 % 3) = -1
(7 % -3) = 1
Note that in both cases, the algebraic quotient is the same (-2). The difference in the remainder results from the implementation-defined sign of the remainder when both operands are of different signs.
The above is the detailed content of Why Does the Modulo Operator Produce Negative Results with Negative Numbers?. For more information, please follow other related articles on the PHP Chinese website!