Hello. I ran into an issue (which I fixed) during the creation of a lab program and was wondering if you all could clarify why it happened. I'd also appreciate it if you could make suggestions as to alternative ways of completing the assignment, since I am not sure if I am making this more convoluted than it needs to be.
The assignment is to create a program that calculates change. The user provides the amount due and the amount received, and the program calculates how many dollars, quarters, dimes, etc, the customer should receive.
Here is what I wrote:
I know it's probably a mess to you guys.Code:#include <iostream> #include <cmath> using namespace std; void main() { int dollars = 0; int quarters = 0; int dimes = 0; int nickels = 0; int pennies = 0; double due; double received; cout << "Please enter the amount due:\n"; cin >> due; cout << "Please enter the amount received:\n"; cin >> received; due = received - due; if ( due >= 1 ) { dollars = static_cast<int>( due ); due -= dollars; } if ( due >= .25 ) { quarters = static_cast<int>( due / .25 ); due -= quarters * .25; } if ( due >= .10 ) { dimes = static_cast<int>( due / .10 ); due -= dimes * .10; } if ( due >= .05 ) { nickels = static_cast<int>( due / .05 ); due -= nickels * .05; } if ( due > 0 ) { pennies = static_cast<int>( due / .01 ); } cout << "Supply the customer with:\n" << dollars << " dollar(s)\n" << quarters << " quarter(s)\n" << dimes << " dime(s)\n" << nickels << " nickel(s)\n" << pennies << " pennies"; cin.get(); cin.get(); }
Anyway, if you change the dollars, quarters, etc, variables to doubles, the program works flawlessly. However, if you retain them as ints and attempt to use a difference of say, .72 between the two values, it indicates that you should use only one penny instead of two. The same is true for a difference of .73, where it suggests 2 pennies instead of 3.
Why does this happen?
Besides the aforementioned curiosity, I would also like to know if there is any way to get rid of all of the if statements, and just in general how I could optimize things.
Thanks guys.