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

int main(void) {
    float change;
    int quarter = 25;
    int dime = 10;
    int nickel = 5;
    int penny = 1;
    int counter = 0;
    int c = 0;
    //user input
    do {
        printf("O hai! How much change is owed?\n");
        change = get_float();
    } while (change < 0);
    //converting to cents
    c = change * 100;
    //calculating coins
    while (c >= quarter) {
        counter = counter + 1;
        c = c - quarter;
    }
    while (c >= dime) {
        counter = counter + 1;
        c = c - dime;
    }
    while (c >= nickel) {
        counter = counter + 1;
        c = c - nickel;
    }
    while (c >= penny) {
        counter = counter + 1;
        c = c - penny;
    }
    printf("Coins are %i", counter);
}

For example when user inputs a value of 4.2 then var change is not storing 420, its storing 4.19999981 as it is a float and this value gets multiplied by 100 and gets stored in int c as 419.How do i fix this,please help.

2

You need to round the result of change * 100. You can do that simply with the round function found in math.h.

For example, round(4.2*100) would return 420, where 4.2*100 gives 419.

| improve this answer | |
  • The reason that you need to round is this. When a float or the result of a float calculation is assigned to an int, the fractional part of the float is truncated. So, something like 419.999998 would be assigned to an int as 419, not 420. – Cliff B Dec 28 '17 at 7:39

You must log in to answer this question.

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