What I want to know is, is this the best implementation of such a program (for a beginner that is)? Given the limitations of floating-point arithmetic, is this the best way to handle converting a given sum of money to its equivalent change?
Miles Davis wrote:What I want to know is, is this the best implementation of such a program (for a beginner that is)?
Given the limitations of floating-point arithmetic, is this the best way to handle converting a given sum of money to its equivalent change?
No. And well done for working out that FP is likely to cause problems (you'd be surprised how many beginners don't). +1.
Tip 1: Use pennies internally for ALL your denominations, since it's the smallest unit you deal with. That allows you to keep everything as integers.
An alternative is to use BigDecimal, but the class is quite clumsy and may distract you from your basic problem.
Tip 2: If you need to accept a number like "49.99" as input, convert it to pennies immediately.
Tip 3: Don't include divisions in your "denomination" variables. Just keep them as constants in pennies.
Tip 4: You shouldn't need any division. This is basically a subtraction exercise.
Hint: if you put the large denominations first, you can simply iterate the values() array in order.
I had to look at all those % calculations for quite a while before I realized they worked, but I guess they do work. Kind of neat in one way. However there's a programming principle called "DRY" which stands for "Don't Repeat Yourself" and your code definitely repeats itself. The others have already alluded to other ways to solve the problem, but it's helpful to think about how the process works before jumping in. And in these days when people pay with credit and debit cards and all kinds of other non-cash payment methods, and when the register tells the cashier exactly how much change to give back, nobody has any experience in making change any more, neither cashiers nor customers.
So here's the process:
Give out $100 bills until you owe less then $100.
Give out $50 bills until you owe less than $50.
Give out $20 bills until you owe less than $20.
Give out... okay, you get the picture. But this is repeating myself in a big way. So you'd write a loop to encapsulate that repeating logic:
For each denomination X (from largest to smallest): give out X until you owe less than X.
That's all you need. Notice that separating dollars from cents doesn't appear in this logic, so doing that is going to complicate things. Value all your denominations in cents (e.g. a $5 bill is worth 500 cents). And also notice that "you owe" in the description of what to do implies that you have to keep track of how much you owe as you give out currency.