Home >Backend Development >C++ >How to Ensure Positive Results When Using the Modulus Operator with Negative Numbers?
Cleverly solve the problem of taking modulo negative numbers
Many programming languages provide the modulo operator (%), which is used to calculate the remainder after dividing one number by another. However, when this operator is applied to negative numbers, unexpected results may occur.
For example, when executing -1 % 3 in a language like C or Java, the result is -1 instead of the expected 2. This is because the modulo operator usually returns the remainder of a division operation, which may be negative for a negative dividend.
To overcome this problem and get the desired behavior, a custom mod function can be implemented:
<code class="language-c++">int mod(int x, int m) { return (x % m + m) % m; }</code>
Using this function, the following calculation results are as expected:
输入 | 预期输出 | 函数输出 |
---|---|---|
-1 % 3 | 2 | mod(-1, 3) = 2 |
-2 % 3 | 1 | mod(-2, 3) = 1 |
-3 % 3 | 0 | mod(-3, 3) = 0 |
How this function works is that it ensures that the result is always positive by adding the modulus to any negative value obtained by the initial modulo operation.
The above is the detailed content of How to Ensure Positive Results When Using the Modulus Operator with Negative Numbers?. For more information, please follow other related articles on the PHP Chinese website!