# Why doesn't greedy input round properly?

In my greedy program, my input is achieved by doing this:

``````    float changeInput = 0;
float changeRounded = 0;

do{
printf("How much change? ");
changeInput = GetFloat();
}while(changeInput <= 0);
``````

This gets me a positive float value which I'm rounding using floatf():

``````changeRounded = roundf(changeInput * 100) / 100;
``````

My issue appears when I go to actually subtract the coins from the total change. Since a total of `1.26` is actually `1.2599999904632568359375` to the computer, it is either leaving off a coin or subtracting an extra penny. This makes my coin count off, and sometimes makes the error 5-10 coins off. Here is how I am counting the coins used:

`````` while(changeRounded > 0) {
printf("%2.30f\n", changeRounded);
if(changeRounded >= .25 ) {
changeRounded -= .25;
coins++;

}else if(changeRounded < .25 && changeRounded >= .1) {
changeRounded -= .10;
coins++;

}else if(changeRounded < .1 && changeRounded >= .05) {
changeRounded -= .05;
coins++;

}else if(changeRounded < .05 && changeRounded > 0) {
changeRounded -= .01;
coins++;

}
``````

My question is, how can I get my float values to be precise to 2 decimal places so that this error doesn't cause my program to be inaccurate?

I have my rounded number as an int, because when you multiply your float with 100 and round it, then you can drop anything that's not a whole number (cents is the smallest coin).

``````change = round(change*100);
cent = (int)change;
``````

Hope this helps.

• Actually this isn't necessary because a function called roundf exists. You can just do: int cent = roundf(change*100); Aug 8 '15 at 5:37
``````changeRounded = roundf(changeInput * 100) / 100;
``````

Why are you dividing by 100?

As the walkthrough says, you want to work with cents. Plus, multiplying by 100 to divide by 100 in the same line of code does absolutely nothing at all, it would do the same if you deleted it. You want to take out the / 100 and work with cents. By dividing, you are now working with dollars, which leads to float imprecision.

One of the takeaways from this pset is the concept of floating point imprecision. You're having trouble getting your floats to be precise, but there is a way you can somehow avoid using floats altogether and work with whole numbers. I highly recommend going back and watching the walkthrough embedded in the greedy specification.

Convert the `float` you got from the user to an `int` to use for the calculations ,That way there will be no room for the extra integers

• Convert which float? No room for the extra...what? Dec 14 '17 at 1:43