You want to find the remainder after you divide two integer values.

int myValue0 =  20 % 10;  // get the modulus(remainder) of 20 divided by 10

int myValue1 =  21 % 10;  // get the modulus(remainder) of 21 divided by 10


myValue0 equals 0 (20 divided by 10 has a remainder of 0). myValue1 equals 1 (21 divided by 10 has a remainder of 1).


The modulus operator is surprisingly useful, particularly when you want to see if a value is a multiple of a number. For example, the code in this recipe’s Solution can be enhanced to detect when a value is a multiple of 10:

for (int myValue = 0; myValue <= 100; myValue += 5)

{

  if (myValue % 10 == 0)

  {

    Serial.println("The value is a multiple of 10");

  }

}


The preceding code takes the modulus of the myValue variable and compares the result to zero 

Here is a similar example, but by using 2 with the modulus operator, the result can be used to check if a value is odd or even:

for (int myValue = 0; myValue <= 10; myValue++)

{

  if (myValue % 2 == 0)

  {

    Serial.println("The value is even");

  }

  else

  {

    Serial.println("The value is odd");

  }

}



This example calculates the hour on a 24-hour clock for any given number of hours offset:

void printOffsetHour( int hourNow, int offsetHours)
{
   Serial.println((hourNow + offsetHours) % 24);
}

You can also use the modulus operator to help simulate floating-point operations. For example, consider the problem described in where dividing 36.3 by 3 yields 12.0999994277 rather than the expected 12.1. You can multiply the two values by 10, then perform the division as an integer operation to get the integer part:
int int_part = 363/30; // result: 12
Next, you can calculate the remainder, multiply it by 100, then divide by the divisor to get the fractional part:
int remainder = 363 % 30; // result: 3
int fractional_part = remainder * 100 / 30;

No comments

Theme images by Dizzo. Powered by Blogger.