0

So my code looks like this:

#include <cs50.h>
#include <stdio.h>
#include <math.h>

int main(void)
{
    // Get change
    printf("How much change is owed? ");
    float change = GetFloat();

    //Retry change
    if (change < 0)
    {
        do
        {
            printf("How much change is owed? ");
            change = GetFloat();
        }
        while (change < 0);
    }

    int rchange = roundf(change*100);

    int coins = 0;

    do
    {
        // Quarters
        if (rchange >= 25)
        {
            rchange = rchange - 25;
            coins = coins + 1;
        }
        // Dimes
        else if (5 < rchange <= 10)
        {
            rchange = rchange - 10;
            coins = coins + 1;
        }
        // Nickels
        else if (1 < rchange <= 5)
        {
            rchange = rchange - 5;
            coins = coins + 1;
        }
        // Pennies
        else if (rchange == 1)
        {
            rchange = rchange - 1;
            coins = coins + 1;
        }
    }
    while (rchange > 0);

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

Whenever I run check50, everything will work properly except 0.41, which gives an output of 3 instead of 4. I'm assuming this is a problem with the rounding, but no matter what I've tried to do to fix it, it still won't work. I would really appreciate it if someone could point me in the right direction here. Thanks!

0
0

For starters, (a < x <= b ) isn't valid. I'm not sure what result it produces, but it won't do what you think. (I believe that rules of precedence will produce the following: a < x is evaluated to either true or false, and that result is inserted, as an int, into result <= c) You need to do two independent tests, and join them logically. ( (a < x) && (x <= b) )

Having said that, look at your logic. There are problems when the change gets down below 25 cents. What happens, for instance at 16 cents? If I read it right, and make the suggested correction, it will fall through all of the tests.

If this answers your question, please click the check mark to accept this and remove the question from the unanswered pool. Let's keep up on forum maintenance. ;-)

You must log in to answer this question.

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