Home >Backend Development >C++ >How Does the Modulo Operator Handle Negative Numbers?
Understanding the Modulo Operator's Behavior with Negative Values
The modulo operator is known to yield different results when used with negative operands. To delve into this, let's consider the following operations:
std::cout << (-7 % 3) << std::endl; // Output: -1 std::cout << (7 % -3) << std::endl; // Output: 1
Rationale According to the ISO Standard
According to ISO14882:2011(e) 5.6-4, the modulo operator (%) yields the remainder from the division of the first expression by the second. However, for integral operands like in our case, the division operator (/) performs integer division, discarding any fractional part.
Mathematical Breakdown
Let's break down the calculations for clarity:
Implementation-Defined Behavior
It's important to note that when both operands are negative, the sign of the remainder is implementation-defined. However, as of ISO14882:2011(e), the behavior is no longer explicitly stated as in its predecessor, ISO14882:2003(e).
The above is the detailed content of How Does the Modulo Operator Handle Negative Numbers?. For more information, please follow other related articles on the PHP Chinese website!