Home > Backend Development > C++ > How to Ensure Positive Results When Using the Modulus Operator with Negative Numbers?

How to Ensure Positive Results When Using the Modulus Operator with Negative Numbers?

Mary-Kate Olsen
Release: 2025-01-13 13:42:44
Original
301 people have browsed it

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template