Reputation: 33
I have a challenge in my programming class where we have to use a void function to calculate the possible coin combinations with a given change value from 1 to 99 cents.
So far my code looks like this:
#include <iostream>
using namespace std;
void computeCoins(int coinValue, int& num, int& amount_left);
int main()
{
//Define varibles then get user input for change
int leftOver, quarters=0, dimes=0, nickels=0, pennies=0, coins=0, originalAmount;
do
{
cout << "Enter change amount: ";
cin >> originalAmount;
leftOver = originalAmount;
} while ((leftOver > 99) || (leftOver < 1)); //Larger than 99 or smaller than 1? If yes, then try again.
//Quarters
computeCoins(25, coins, leftOver);
quarters = coins;
//Dimes
computeCoins(10, coins, leftOver);
dimes = coins;
//Nickels
computeCoins(5, coins, leftOver);
nickels = coins;
pennies = leftOver;
cout << originalAmount << " cent/s could be given as " << quarters << " quarter/s, " << dimes << " dime/s, " << nickels << " nickel/s, " << " and " << pennies << " pennies.";
cout << endl;
system("PAUSE");
return 0;
}
void computeCoins(int coinValue, int& num, int& amount_left)
{
//Using the specified coin value, find how many can go into it then subtract it
while (amount_left % coinValue == 0)
{
// Still dividable by the coin value
num += 1;
amount_left -= coinValue;
}
}
Now my problem is when I run the program, it returns a very large negative value for quarters, dimes, and nickels. I'm positive it has something to do with how my loop conditions are set up, does anyone have an idea why this is happening?
Upvotes: 1
Views: 1106
Reputation: 15872
As I read your question, it appears you are supposed to look for a way to get all possible combinations. Oliver Matthews' answer handles the first part of that (figuring out how many of a given type of coin you can fit in the change), but you'd have to do that in a loop that checks various other combinations (e.g. all pennies, all nickels w/pennies, all dimes w/pennies, all quarters w/pennies, etc.) and need a method for returning the combinations (e.g. return a vector of some structure/class that handles the coin counts through an output parameter - that is, a vector by reference).
Upvotes: 0
Reputation: 7803
Two issues: one undefined coins initial value. Two the amount_left % coinValue == 0
part - I think you mean amount_left >= coinValue
Although there is no need to keep iterating in that function
void computeCoins(int coinValue, int& num, int& amount_left)
{
// add as many coinValues as possible.
num += amount_left / coinValue;
// the modulus must be what is left.
amount_left = amount_left % coinValue;
}
Note that (among other things), you'd be better off using unsigned ints
for quantities of things.
Upvotes: 2