Hello. I'm brand new to the forum. I have been lingering and searching for a while but never opted to join up.
I have to write a program that will determine the change to be given back to a customer based on input values of purchase amount and cash given as payment. The program will also tell the number and type of coins to be dispensed as change. (the purchase amount and payment have be set up sequentially in an input file).
I have used a while loop and if statements so far, though, I'm sure there are much simpler ways. For a few instances it works. However, for others, the coins dispensed are off by a penny.
floating points are approximations. You should never use == or != with floating points, and you should always expect some rounding errors.
Instead of using floating points for this, I would use integers. And instead of representing the number of dollars, represent the number of cents instead.
for example, instead of float onedollar = 1.00; do int onedollar = 100;
Then when printing, just divide by 100 to get the dollars, and mod by 100 to get the cents:
If this is a real project (not just homework), I suggest you do the hard work of writing your own class in the beginning to save you headaches later on.
For money, ultimately, you will need to write your own class around integer (as suggested by Disch) or around a prepackaged Decimal class like this:
Once you do interest compounding or any kind of general division or multiplication; say, divide $1.00 in 3 ways, you will have to write your own algorithm on how you want to deal with that last penny! In other words, you want to implement your own operator*() and operator/(), possibly with support classes to help you minimize rounding errors.
Best to deal with that in a controlled test-environment, before you end up in debugging-hell, tracking phantom pennies through giant accounting ledgers!