Confused about modulus

This code is not producing expected results. I'm dividing by ten and expecting count of 10's and remainder.

for (int K = 0; K<= 87; K++) {

Software submitted post before finishing:

This code is not producing expected results. I'm dividing by ten and expecting count of 10's and remainder.

for (int K = 0; K<= 87; K++) {

Use the code tag in the reply editor to properly post your code and try again, please.

If I hit a tab the post is submitted

This code is not producing expected results. I'm dividing by ten and expecting count of 10's and remainder.

for (int K = 0; K<= 87; K++) {
Q=K/10; //generate number of 10's
P=Q%10; //display remainder
}

K=10 gives Q=1; P=10- - I want Q=1; P=0
K=18 gives Q=1, P=10- - I want Q=1; P=8

My C and C++ textbooks don't address it. So what face palm idea am I missing?

  1. Get and store remainder
  2. Floor divide the number by 10 and store it back into itself
  3. Repeat while number is greater than 0

Please use the code tag to add code:
image

This would surprise me, it's a pretty standard exercise.

Should that not be:

P = K % 10;  // Display remainder.

I normally use the code tag, but for three lines of code that resides on a separate computer isolated from the internet I didn't want to transfer it to a stick to trade between machines.

You can edit your posts and put the code in tags now though.

I agree with @jfjlaros, that should be

   Q=K/10; //generate number of 10's
   P=K%10; //display remainder

in this case, you could also

   Q = K / 10;
   R = K - 10 * Q;

and leave the mod operator out of the picture.

a7

Thanks for the help; problem solved.

The division operator (/) gives Quotient (Q) when the number K is divided by N.
The modulus operator (%) gives Remainder (R) when the number K is divided by N.

For example: Given: K = 87, N = 10
Q = 8
R = 7

Codes:

for(int K = 0; K <= 87; K++)
{
     Serial. print("Quotient (Q): "); Serial.println(K/10);
     Serial. print("Quotient (R): "); Serial.println(K%10);
     Serial.println();
}

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.