Shawn wrote:
> Hello all,
> I apologize as I am sure this has probably been dealth with before...
> but I am doing an exercise from "Practical C Programming" and I have
> been unable to get it to work perfectly due to problems with floating
> point arithmetic and I am looking for a way to solve it. See the code
> below...
> Given a certain amount of change (below $1.00) the program will tell
> you how many of each coin you will need to get that amount. The
> program is "working" in that the logic appears correct and it DOES
> work for some numbers, but for others, it is not. The problem appears
> to be that 0.01 as I see it, is not being represented in memory.
> I have done some searching online and I am sure this is a common
> problem but I just can't seem to find the workaround...
First, the question has, as you suspect, arisen before.
In fact, it arises frequently, and therefore has a place in
the comp.lang.c Frequently Asked Questions (FAQ) list
http://www.eskimo.com/~scs/C-faq/top.html
Start with Question 14.1, and then look at 14.4 and 14.5.
Once you've digested that, you'll have realized that
floating-point arithmetic is trickier than it first appears.
Floating-point is very good at dealing with proportions and
ratios and logarithms and the like, but is not well-suited
to counting problems -- problems involving discrete "things,"
if you like. So what's the work-around? Well, can you think
of a way to restate your original problem in terms of discrete
indivisible units instead of fractions of something-or-other?
Hint: What should your program do if someone asks for $0.14159
in change?
--