This is a simple currency change calculcator in C for a course I'm taking (CS50).
It works pretty well, until you submit the values 0.15
, 4.2
and 4.3
(those are the ones I caught so far), the program freezes, doesn't output any results. I have to CTRL + C
to force quit.
If I try another number, say 0.41
I get the correct answer.
Why is this happening?
#include <cs50.h>
#include <stdio.h>
int main (void) {
printf("How much change do you owe: ");
float amount;
// (;;) represents an infinite loop
for (;;)
{
amount = GetFloat();
// if user's input is negative, the script will break and prompt the user to enter a positive value.
if (amount >= 0) {
break;
}
printf("Please provide a positive value: ");
}
float cents = 100.0 * amount;
float quarter = 0;
float dime = 0;
float nickel = 0;
float penny = 0;
// I used the shortcut to represent (cents = cents + 25.0)
while (cents > 0) {
if (cents >= 25.0) {
cents -= 25.0;
quarter += 1;
} else if (cents >= 10.0) {
cents -= 10.0;
dime += 1;
} else if (cents >= 5.0) {
cents -= 5.0;
nickel += 1;
} else if (cents >= 1.0) {
cents -= 1.0;
penny += 1;
}
}
float coins = quarter + dime + nickel + penny;
printf("%f\n", coins);
}
Aucun commentaire:
Enregistrer un commentaire