0

I made a very simple program that distributes back change(quarters, dimes, nickels, and pennies) to the user. It distributes back the same amount, value, in change that the user inputs in cash. It was performing well until I input: 0.59 So, after tinkering with the program a little I was able to fix this issue. However, I still do not understand what exactly I did right to fix it...

int change_owed(float amount) {

int change, coins;
change = coins = 0;

change = (float)(amount * 1000000.0);
change /= 10000;

Any explanation would be great. Also, I apologize if this question has already been asked. Upon searching stackoverflow, I could not find a solution.

Lift alots
  • 33
  • 6
  • We need more code than this, what types are change and amount? – Sarima Mar 18 '15 at 22:25
  • 1
    The cast probably doesn't do anything in this code example, but the background here could help: http://stackoverflow.com/questions/2100490/floating-point-inaccuracy-examples – Douglas Mar 18 '15 at 22:51
  • 1
    change is an integer, and amount is a float. – Lift alots Mar 18 '15 at 23:10
  • 1
    Then please update the question to say that, preferably by showing the actual declarations of `change` and `amount`. – Keith Thompson Mar 18 '15 at 23:48
  • 1
    Programs that deal with money must NEVER use floating point values, ever. Floats (and doubles) are for higher math, not adding and subtracting amounts that need to be exact. – Lee Daniel Crocker Mar 19 '15 at 00:59

1 Answers1

2

The problem is that there is no exact representation of 0.01 as a floating point number, so there are rounding errors when computing change. The ideal solution is to avoid using floating point numbers altogether. Use fixed point arithmetic instead.

As an example, instead of a floating point number like 3.45 to represent three dollars and forty-five cents, you can use the integer value 345. This type of representation is known as fixed-point because there's an assumed decimal point before the second-to-last digit.

The following sample program shows one way to read a dollar amount (like 3.45) as a fixed point number.

int main( void )
{
    int dollars, cents, count, amount;

    printf( "Enter amount: " );
    fflush( stdout );
    count = scanf( "%d.%d", &dollars, &cents );

    if ( count == 1 )
        amount = dollars * 100;
    else if ( count == 2 && cents < 100 )
        amount = dollars * 100 + cents;
    else
        amount = 0;

    printf( "%d\n", amount );
}
user3386109
  • 34,287
  • 7
  • 49
  • 68