0

I seem to be having trouble using modulo as conditions inside of while loops.

int main()
{
    float n;
    do
{
   n = get_float("How much change is owed? ");
} 
while(n < 0);

int cents = round(n * 100);
int coinsUsed = 0;

while (cents % 10 == 25)
{
    cents -= 25;
    coinsUsed++;
}
while (cents % 10 == 0)
{
    cents -= 25;
    coinsUsed++;
    printf("%i", coinsUsed);
}
while (cents % 5 == 0)
{
    cents -= 5;
    coinsUsed++;
}
for (int i = 0; i < cents; i++)
{
    coinsUsed++;
}

printf("%i\n", coinsUsed);
}

I try to use a modulo operator to check to see if the number can be divided by 25 for quarters, 10 for dimes, etc. However, when I run the code, I get an overflow error as the while loop continues to operate forever.

1
  • Wrong modulo operand while (cents % 10 == 25)? (and wrong truth test, compare it to the other sentences). Commented Jan 31, 2020 at 22:25

1 Answer 1

1

Why are you using modulo for this? It produces an unreliable result in this usage. Further, the actual numbers don't make sense.

The modulo function returns the remainder after an integer division. So, for example, say that you're doing while (cents % 10 == 5) If cents were $1.05, it would be true, but if cents were $1.06, it would be false. In both cases, there are lots of coins left to be processed.

Next, there's this. while (cents % X == Y) Because of the way % works, Y cannot be larger than X. If you don't understand why, you need to study how modulo works.

No, modulo is not the right mechanism for this test. It does have a different use in this program though, one that is very efficient and useful!

And, as @DinoCoderSaurus pointed out, mismatched values for the quarters test.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .