Modulus Function: Difference between revisions
Jump to navigation
Jump to search
(Created page with "A modulus (modulo, mod) is simply the remainder when dividing one number by another. When we divide 7 by 2 the result is 3 with 1 remainder. In C / C++ the operand <code>%</code> returns the modulus between two numbers, for example: <pre> Serial.println(7 % 2); >> Outputs ‘1’. </pre> One ‘gotcha’ with the modulus operation is that it returns the modulus using the same sign as the dividend. The sign of the divisor is irrelevant. The examples below...") |
No edit summary |
||
Line 18: | Line 18: | ||
</pre> | </pre> | ||
Consider the function below. It tests to see if a number is odd by checking the modulus is one. Of course, this will fail if the | Consider the function below. It tests to see if a number is odd by checking the modulus is one. Of course, this will fail if the <code>numberToTest</code> is negative. | ||
<pre> | <pre> |
Latest revision as of 01:30, 17 August 2024
A modulus (modulo, mod) is simply the remainder when dividing one number by another. When we divide 7 by 2 the result is 3 with 1 remainder.
In C / C++ the operand %
returns the modulus between two numbers, for example:
Serial.println(7 % 2); >> Outputs ‘1’.
One ‘gotcha’ with the modulus operation is that it returns the modulus using the same sign as the dividend.
The sign of the divisor is irrelevant. The examples below shows this in action:
Serial.println(7 % 2); >> Outputs ‘1’. Serial.println(-7 % 2); >> Outputs ‘-1’. Serial.println(7 % -2); >> Outputs ‘1’. Serial.println(-7 % -2); >> Outputs ‘-1’.
Consider the function below. It tests to see if a number is odd by checking the modulus is one. Of course, this will fail if the numberToTest
is negative.
bool isAnOddNumber(int numberToTest) { return numberToTest % 2 == 1; }
Changing the function to test for a non-zero number - a one or a negative one – accounts for both positive or negative inputs.
bool isAnOddNumber(int numberToTest) { return numberToTest % 2 != 0; }