I've seen this particular C program mentioned quite a bit, albeit in some different forms. However I cannot seem to identify the source of my problem, or find another answer that helps. The program compiles and even executes correctly except for a single input: 4.2
The program appears to count the minimum number of coins needed to make the change entered as input, except for 4.2. It outputs 22 instead of 18 as it should (16 quarters, 2 dimes).
Any thoughts? I'm auditing an online course, no credit/no academic dishonesty issues.
//quarters, dimes, nickels, and total number of coins. a is float input for exact change.
printf("Hello, how much change do I owe you?\n");
a = GetFloat();
//converting float a to an integer i
//four 'while' loops checking quarters nickels dimes pennies and adding to coin count while
while(i>=10 && i<25)
while(i>=5 && i<10)
while(i>0 && i<5)
//printing sum of each coin type
You just counterfeited by floating point precision.
a = 4.2; // say
it looks something like
a = 4.19999981
i= a*100; is assigned
i instead of
420 (what you are expecting).
Solution You need to convert float
a into integer :
(int)(x + 0.5)
So, instead of
i= a*100 try
i= a*100 + .5;