我的编程课中有一个挑战,我们必须使用void函数来计算可能的硬币组合,给定的变化值从1到99美分 .
到目前为止我的代码看起来像这样:
#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;
}
}
现在我的问题是当我运行程序时,它会返回一个非常大的负值,包括四分之一,硬币和镍币 . 我很肯定它与我的循环条件设置有关,有没有人知道为什么会这样?
2 回答
两个问题:一个未定义的硬币初始值 . 两个
amount_left % coinValue == 0
部分 - 我想你的意思是amount_left >= coinValue
虽然没有必要继续迭代该函数
请注意(除其他事项外),最好使用
unsigned ints
来处理大量事物 .在我阅读你的问题时,似乎你应该寻找一种方法来获得所有可能的组合 . Oliver Matthews的回答处理了第一部分(弄清楚你可以在改变中使用多少特定类型的硬币),但是你必须在一个检查各种其他组合的循环中做到这一点(例如所有的便士,所有的镍币都是硬币,所有硬币都是硬币,所有四分之一都是硬币等等,并且需要一种方法来返回组合(例如,通过输出参数返回一些处理硬币计数的结构/类的向量 - 是,通过引用的向量) .