| Tilman Bohn 2005-02-25, 4:00 am |
| [X-post and Followup-To set to clj.help]
In message <1109304817.794736.114220@f14g2000cwb.googlegroups.com>,
reuben.nantogmah@gmail.com wrote on 24 Feb 2005 20:13:37 -0800:
> Hi,
>
> I would appreciate any help I can get with this. The program accepts a
> range of numbers (dollors) and provides a combination of the least
> amount of bills and coins needed to make change for the input. This
> program works for most numbers but there is a bug. try 19.99 and you
> will see that the change is a penny short. Thanks for your help.
You are using doubles for doing calculations on numbers that have
simple representations in base 10. This simplicity, however, is
misleading, as their representations in base 2 are not generally as
simple. For example, work out what the binary representation of 0.1 is,
and you will quickly see what your problem is.
The immediate lesson you're supposed to learn from this exercise is to
use integer types internally when dealing with money (or anything else
where exact results are imperative). Can you see how to do this in your
case?
The deeper lesson you're supposed to learn from this exercise is to
always be aware of the internal representation of the data you're
working on, be aware of the mechanics of its manipulation, and be aware
of possible limitations on accuracy. And choose the representation most
appropriate for the problem at hand.
Having said all that, let me point out I haven't closely checked your
code after seeing the use of doubles, so I don't know if there might be
other algorithmic mistakes. If so, you'll have to go back to them once
you have the representation of your money right. But the latter most
definitely needs to be fixed first.
--
Cheers, Tilman
`Boy, life takes a long time to live...' -- Steven Wright
|