xboxscene.org forums

Author Topic: I Need Help With A Little Buggy!  (Read 43 times)

joseph_hac

  • Archived User
  • Sr. Member
  • *
  • Posts: 415
I Need Help With A Little Buggy!
« on: August 13, 2004, 08:15:00 AM »

Hey guys,

I wrote a little Java applet to help me learn the language. The program itself is trivial. The user enters in an amount of change and the program outputs the amount of each coins denomination that needs to be dispensed to make the change. It's jsut a simple greedy algorithm. There's a bit of a twist, however, an extra coin has been thrown into the loop. The Jonnie. It's worth $1.21.

You can view the applet HERE.

The problem I'm having is that if you inputa change amount of say 0.08, the program returns that one nickle and two pennies are used. It leaves out the last penny. When stepping through the program, I noticed that once it get's down to the pennies, it subtracts 0.01 from 0.03 and gets 0.0199999999967. Why would this happen? All three variables in the expresion are double.

I have implemented this same program in a C# console app and have the same result. I know this isn't Xbox development, but could you please help a fellow code monkey out.

The source can be viewed HERE.
Logged

JbOnE

  • Archived User
  • Full Member
  • *
  • Posts: 242
I Need Help With A Little Buggy!
« Reply #1 on: August 15, 2004, 01:47:00 AM »

when you get past the nickel check instead of doing a penny check why don't you try something like this...

m_numPennies = (int)( tmpAmount * 10 );

i don't do java so i don't know if you can cast in it - but you get the idea.
you'll only have pennies if your remainder is less than 0.05, so multiplying the remainder * 10 will give you a whole number of pennies needed. think outside the bun  wink.gif
Logged

code_monkey

  • Archived User
  • Newbie
  • *
  • Posts: 1
I Need Help With A Little Buggy!
« Reply #2 on: August 29, 2004, 11:36:00 AM »

The reason that your last penny is stored as a fraction of a penny and not as 0.01 is because the floats (or doubles) are approximated with binary.  It just like converting a natural number (1, 2, 3, 4, ...) from decimal to binary, except you have to halve the posible value instead of doubling it.  For example:  
00000001 = 0.5
00000010 = 0.25
00000011 = 0.75

It's not exactly like that because a double is made of a sign bit, an exponent and a mantissa but the idea is the same.  You can see the same behavior if you have a for loop adding 0.1 ten times and checking to see if it's equal to 1.
Logged