Home >Backend Development >C++ >How Does the Modulus Operator Handle Negative Numbers in C/C /Obj-C?
Modulus Operator Handling Negative Numbers in C/C /Obj-C
Unlike in mathematics, the modulus operator (%) in C-derived languages exhibits inconsistent behavior when applied to negative numbers. This discrepancy arises from the ambiguity surrounding the sign of the remainder.
Implementation-Defined Behavior
According to the C 03 standard, the sign of the remainder when both operands are negative is implementation-defined. This means that different compilers and platforms may produce varying results for operations such as (-1) % 8 and fmodf(-1, 8).
Reliable Expression
Regardless of the implementation, the following expression holds true:
(a / b) * b + (a % b) == a
This expression states that the dividend (a) can be reconstructed from the quotient (a / b) and the remainder (a % b).
Solution
One approach to ensure consistent behavior for negative operands is to calculate the remainder as follows:
<code class="cpp">int mod(int a, int b) { if (b < 0) return -mod(-a, -b); int ret = a % b; if (ret < 0) ret += b; return ret; }</code>
This function handles negative operands by negating both operands in case b is negative. The remainder is calculated as a % b. If the remainder is negative, it is adjusted by adding the absolute value of b. This ensures that the result is a non-negative remainder that satisfies the abovementioned reliable expression.
In this way, mod(-1, 8) would return 7, and mod(13, -8) would return -3, adhering to the expected mathematical behavior.
The above is the detailed content of How Does the Modulus Operator Handle Negative Numbers in C/C /Obj-C?. For more information, please follow other related articles on the PHP Chinese website!