So i am trying to make a cashier program where the user enters the amount of money entering in a cash register and wanted to return the amount of change to the customer but can't seem to find the proper way to do it. I know I'm doing it wrong but can someone help me out, please. For example, if the customer gives the machine 220 dollars I wanted it to give 100 100 and 20 dollars back similar to a real cash register thank you in advance.
what if owed a dollar flat, 1.00? look at line 73 again.
this seems very complex.
how about this:
1 2 3 4 5 6 7 8 9 10 11 12 13
double amounts[] = {100.0, 50.0, 20,10.0, 5.0, 1.0, 0.5, 0.25,0.1, 0.05, 0.01}; //did you leave off 50 cent pieces on purpose?
double value = 123.45;
int index = 0;
while (value)
{
if(value >= amounts[index];
{
value -= amounts[index];
//dispense amounts[index] -- eg hand them a single $100 bill in this case.
}
else index++;
}
this will work most of the time for small amounts. because you chose to use doubles, there may occasionally be a round off error here, breaking the code or causing various issues.
i highly recommend using long long instead and letting 1 == a penny instead. that ensures everything is exact. If required to enter and print as doubles, convert and do the work as long long and show the user floating point values.
i highly recommend using long long instead and letting 1 == a penny instead
Good advice.
Working with integers will making giving back change a lot easier - you'll be able to more easily use % (remainder). If someone gives you $220, then the program will take it in as 22,000. You'll then send this number down a "ramp" of all the possible change you can give, starting from largest to smallest:
1 2 3 4 5 6 7 8 9 10 11 12 13
int main()
{
int cash = 22000;
if(cash>10000) //if $220 is bigger than $100
{
int temp = cash/10000;
cash %= 10000; //Remainder is 2000, which is $20
std::cout << "You got: " << temp << " $100 bills\n";
}
//.... etc
}