0

My code gets the wrong output for .41 and .01 when run through check50. why?

#include <cs50.h>
#include <stdio.h>
#include <math.h>
int main(void) {
    float cents;
    int quarter = 25;
    int dime = 10;
    int nickel = 5;
    int penny = 1;
    int amt_of_coins = 0;

    printf("O hai! How much change is owed?\n");
    do {
        cents = get_float();
    }
    while (cents < 0);



    cents = (int)(round(cents*100));

    while(cents >= quarter ) {
        cents-= quarter;
        amt_of_coins += 1;
     }
    while (cents >= dime && cents< quarter) {
        cents-= dime;
        amt_of_coins += 1;
    }
        while (cents >= nickel && cents< dime) {
        cents-= nickel;
        amt_of_coins += 1;
    }
        while (cents > penny && cents< nickel) {
        cents-= penny;
       amt_of_coins += 1;
    }
    printf("%i\n", amt_of_coins);
     return 0;
}
0

Your last while loop isn't going to count pennies correctly if you have 1 cent left over (as in the inputs $0.01 and $0.41).

while (cents > penny ...

When cents is 1, this loop won't run at all because 1 > 1 is false. You need:

while (cents >= penny ...

Also, you don't need the second conditions in your loops. After the previous loop finishes, you already know that the second conditions will be true.

You must log in to answer this question.

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