1

I know there are some similar questions already but when I went through the forum I didn't actually find an explanation for the problem I am experiencing. Here is a sample of the code:

float change = GetFloat();
int coins = 0;
//checking if the user input is valid then continuing
while (change>=0.25)
{
   coins=coins + 1;
   change = change - 0.25;
}
//the same for dimes and nickels
while (change>=0.01)
{ 
      coins = coins + 1;
      change = change - 0.01;
} 

It's working fine for almost all test scenarios except the ones that involve the pennys, for example: in case of 0.41 it gives 3 instead of 4, the input 0.01 also isn't correct etc. Is it still a float number imprecision? Because it works ok for everything except the pennys (I have 0.83 in the gradebook as a result). I will appreciate your help and explanation as to where the problem lies :)

1

This is a really good use case for printf debugging, or using GDB. If you put some printf's in your code in this area, I'm sure you will see the problem surface quickly.

Print your float value once, immediately after GetFloat(), then try adding some more printf's to your statement for subtracting the pennies. If the issue is a rounding issue with floats, you should see it immediately after GetFloat when you print the value to the screen. If it's an issue with your penny logic, you should see it later as it is subtracting the pennies.

while (change>=0.01)

{ 

//printf coins before
coins=coins + 1;
//printf coins after

//printf change before
change =change - 0.01;
//printf change after

}
12
  • Thank you for you idea, actually when I do that for example for 0.41 it just prints out 1,2,3,3. Meaning it doesn't count the penny coins the second time it loops...
    – GiP
    Nov 4 '14 at 19:02
  • what happens when you use an initial value of 0.01
    – lethaljd
    Nov 4 '14 at 19:07
  • it prints out only a 0 despite the fact that I included a printf in every loop to see what happens. Or when I test it with 0.26 (a quarter and a penny, therefore it should count 2 coins), it just counts 1 coin
    – GiP
    Nov 4 '14 at 19:09
  • It sounds like you are getting hit by the rounding issue. If you enter 0.01 and it prints out a value of 0, that's it, right?
    – lethaljd
    Nov 4 '14 at 19:11
  • You're right but why only for the penny?
    – GiP
    Nov 4 '14 at 19:13

You must log in to answer this question.

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