0

Why does this fail one of the tests? (when cash is 4.20) It gives 22 instead of 18

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

int main(void){
int num_coins = 0;
float cash;

do{
printf ("Please enter to amount of cash to calculate: ");
cash = get_float();
} while (cash < 0.0);

cash = cash * 100;

while (cash >= 25){
   cash = cash -25;
   num_coins++;
}

while(cash >= 10){
    cash = cash - 10;
    num_coins++;
}

while (cash >= 5){
    cash = cash - 5;
    num_coins++;
}
while (cash >= 1){
    cash = cash - 1;
    num_coins++;
}
printf("%i\n", num_coins);

}
1

Recurring theme in this forum, it is a problem of inherent accuracy to the numbers of type fload or double, the machine causes a truncation, rounding in an inadequate way for our purposes such numbers, I strongly recommend using the function round and a new variable of type int:

int newcash = round(cash*100);

You must log in to answer this question.

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