我在我的編程類中有一個挑戰,我們必須使用void函數來計算可能的硬幣組合,其中給定的變化值爲1到99美分。使用while循環的C++可能的硬幣組合
到目前爲止,我的代碼如下所示:
#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;
}
}
現在我的問題是,當我運行程序,它返回宿舍,助攻和鎳非常大的負值。我很積極,它與我的循環條件如何建立有關,有沒有人知道爲什麼會發生這種情況?
您是否嘗試過調試到您的程序並逐步瞭解它實際上在做什麼? –
你還沒有初始化'硬幣'。所以它可能使用垃圾值。 – Vandesh
我在調試過程中使用了幾個斷點,從我在循環中看到的情況來看,它似乎正確地計算了模塊化的劃分。 – DigitalMammoth