let's say there is 4 50c coin, 2 20c coins, 1 10c coin and 1 0.05c in my program. i have problem to withdraw the coin. if i want withdraw $2, 4 50c will come out and the 50c will be zero << i have no problem with that part. then i want to withdraw $0.50 there should be 2 20c and 1 10c. my problem is that instead of 2 20c and 1 10c my program still show up 50c as the output.
A few problems I see.
1) Line 7: You don't need the while loop at all.
2) Line 13: You don't need the while loop here either (or in any of the cases).
3) What if calc is not a multiple of 5? Your loop relies on calc going to exactly 0. You didn't show us the declaration for calc. If calc is a floating point type (not int), you could also have approximation problems.
4) Lines 12-18: You don't account for the possibility that a1 could be greater than coins50. In that case coin50 goes negative. Same problem applies in each of the other cases.
All these cases have exactly the same logic. Consider making a function.
#include <iostream>
#include <cstdlib>
usingnamespace std;
void dispense_coins (int & calc, int val, int & cnt)
{ int a1;
if (cnt <= 0)
return; // no coins to dispense
a1 = __min(cnt, calc / val); // Don't dispense more coins than we have
calc -= a1*val;
cout << val << "c x " << a1 << endl;
cnt -= a1;
}
int main()
{ int coin50=4;
int coin20=2;
int coin10=1;
int coin05=1;
int calc = 125; // Some value to dispense
dispense_coins (calc, 50, coin50);
dispense_coins (calc, 20, coin20);
dispense_coins (calc, 10, coin10);
dispense_coins (calc, 5, coin05);
if (calc > 0)
cout << calc << " could not be dispensed" << endl;
system ("pause");
}
my calc is floating point type. when i try to change the code to double, then there is problem. When i want to withdraw 1.40, 4 $0.50c dispence and 1 $ 0.20c and 1 $0.05 and $0.05 cannot be dispence. suppose 4 0.5c and 2 0.20c only dispence.
As I mentioned in my previous post, float and double are approximations. Doing a compare equal between two approximations generally will not result in a true condition.
The code I posted above works correctly with calc as an int.
1 2 3 4 5
Amount to dispense: 140
50c x 2
20c x 2
10c x 0
5c x 0