Optimal Change Calculator TIPS for easier expansion
Jan 18, 2017 at 12:17am UTC
So i wrote a program to calculate the optimal change to give for different amounts of change in pence and was wondering how i could implement the checks in the function in a way that i can expand the amount of checks on different coins without having to put more blocks of hard code in.
Any tips welcome :)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
#include <iostream>
using namespace std;
// REMAINDER //
int amountLeft;
// Array For Coins //
int coinArray[6]= {50,20,10,5,2,1};
// GOES THROUGH EACH COIN TO CALCULATE OPTIMAL CHANGE IN PENCE GBP //
void moneySort(int money)
{
int amountOf = money / 50;
cout << amountOf << " x50p" <<endl;
amountLeft = money - (amountOf*50);
amountOf = amountLeft / 20;
cout << amountOf << " x20p" <<endl;
amountLeft = amountLeft - (amountOf*20);
amountOf = amountLeft / 10;
cout << amountOf << " x10p" <<endl;
amountLeft = amountLeft - (amountOf*10);
amountOf = amountLeft / 5;
cout << amountOf << " x5p" <<endl;
amountLeft = amountLeft - (amountOf*5);
amountOf = amountLeft / 2;
cout << amountOf << " x2p" <<endl;
amountLeft = amountLeft - (amountOf*2);
amountOf = amountLeft / 1;
cout << amountOf << " x1p" <<endl;
amountLeft = amountLeft - (amountOf*1);
}
int main()
{
//VARIABLES//
int change = 0;
cout << "Enter your change in pence: " << endl;
cin >> change;
moneySort (change);
cout << amountLeft;
return 0;
}
Jan 18, 2017 at 2:46am UTC
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
#include <iostream>
#include <vector>
constexpr auto coinArray {50, 20, 10, 5, 2, 1};//coins
std::vector<unsigned int > moneySort(unsigned int money);
int main()
{
for (auto & elem : moneySort(86))
{
std::cout << elem << " " ; // add a column header to identify coins
}
}
std::vector<unsigned int > moneySort(unsigned int money)
{
std::vector<unsigned int > change;
unsigned int temp{};
for (auto & elem : coinArray)
{
temp = money / elem;
change.push_back(temp);
money %= elem;
}
return change;
}
Topic archived. No new replies allowed.