I have just began to learn C. I am writing a program that gives change back to the customer in quarters, nickels, dimes and pennies. For some reason when the while
loop reaches 0 it does not break.
EDIT: This question is very similar to another question already on SO (Is floating point math broken?). I would keep this question for those searching for answers regarding the while loop, like myself, who had no idea the floating point number was causing the infinite while loop.
#include <stdio.h>
#include <cs50.h>
int main(void){
float val;
int quarters = 0;
int dimes = 0;
int nickels = 0;
int pennies = 0;
printf("How much change is due?: \n");
val = GetFloat();
while (val > 0){
if (val >= 0.25){
quarters += 1;
val -= 0.25;
}
else if (val >= 0.1) {
dimes += 1;
val -= 0.1;
}
else if (val >= 0.05){
nickels += 1;
val -= 0.05;
}
else if (val >= 0.01){
pennies += 1;
val -= 0.01;
}
printf("%f \n", val);
}
printf("Quarters: %i\n", quarters);
printf("Dimes: %i\n", dimes);
printf("Nickels: %i\n", nickels);
printf("Pennies: %i\n", pennies);
return 0;
}
Any suggestions on how to handle?