Math Help - Making change

1. Making change

I need to figure out the math for this so I can enter it into a Java program.

I have 2 inputs, Amount Owed and Amount Paid. Then from that I get Total change (Amount Paid - Amount Owed). So if I have 500 Amount Paid and 272 Amount Owed, then Total Change is 228.

Now from that I need to figure out how to convert that into dollars, quarters, dimes, nickels, pennies. So 228 would be 2 dollars, 1 quarters, 0 dimes, 0 nickels, 3 pennies. 844 would be 8 dollars, 1 quarters, 1 dimes, 1 nickels, 4 pennies.

If I do Total Change / 100 and then have the program round to the whole number, I'll get 2 for dollars (228 / 100). I don't know how to write out the math so that it will subtract 200 and then move onto quarters and then to dimes, etc. I can't just say -200, because that wouldn't work if the input for Amount Paid is more than 200.

2. Re: Making change

Originally Posted by Jerick
I need to figure out the math for this so I can enter it into a Java program.

I have 2 inputs, Amount Owed and Amount Paid. Then from that I get Total change (Amount Paid - Amount Owed). So if I have 500 Amount Paid and 272 Amount Owed, then Total Change is 228.

Now from that I need to figure out how to convert that into dollars, quarters, dimes, nickels, pennies. So 228 would be 2 dollars, 1 quarters, 0 dimes, 0 nickels, 3 pennies. 844 would be 8 dollars, 1 quarters, 1 dimes, 1 nickels, 4 pennies.

If I do Total Change / 100 and then have the program round to the whole number, I'll get 2 for dollars (228 / 100). I don't know how to write out the math so that it will subtract 200 and then move onto quarters and then to dimes, etc. I can't just say -200, because that wouldn't work if the input for Amount Paid is more than 200.
The greedy algorithm will do for making change :

Code:
Ndollars=floor((TotalChange)/100);
RemainingChange=TotalChange-100*Ndollars;

Nquarters=floor(RemainingChange/25);
RemainingChange=RemainingChange-Nquarters*25;

:
:
CB

3. Re: Making change

Ah, that seems to work. Thanks!

Can you explain why I need to -100 in this case, but not the others?

"RemainingChange=TotalChange-100*Ndollars;"

4. Re: Making change

Originally Posted by Jerick
Ah, that seems to work. Thanks!

Can you explain why I need to -100 in this case, but not the others?

"RemainingChange=TotalChange-100*Ndollars;"
There are 100 cents in a dollar, in the next section you have -Nquarters*25 (for consistencey the order could have been the other way around...)

CB

5. Re: Making change

Ohh... order of operations. Thanks.