2013-10-07 22 views
0

我在我的編程類中有一個挑戰,我們必須使用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; 
    } 
} 

現在我的問題是,當我運行程序,它返回宿舍,助攻和鎳非常大的負值。我很積極,它與我的循環條件如何建立有關,有沒有人知道爲什麼會發生這種情況?

+2

您是否嘗試過調試到您的程序並逐步瞭解它實際上在做什麼? –

+3

你還沒有初始化'硬幣'。所以它可能使用垃圾值。 – Vandesh

+0

我在調試過程中使用了幾個斷點,從我在循環中看到的情況來看,它似乎正確地計算了模塊化的劃分。 – DigitalMammoth

回答

2

兩個問題:一個未定義的硬幣初始值。兩個amount_left % coinValue == 0部分 - 我想你的意思amount_left >= coinValue

雖然沒有必要繼續在迭代該功能

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; 
} 

需要注意的是(除其他事項外),你會更好使用unsigned ints的數量東西的。

+0

沒關係,實際上修復它。從現在起我應該更多地考慮「奧卡姆剃刀」。 – DigitalMammoth

+0

不需要 - 由於您將整數分開,因此C標準表示結果將始終朝向0. –

+0

由於您需要計算每種類型硬幣的數量,而不是所有硬幣的總數,因此num + = '應該是'num ='。 – Bull

0

當我看到你的問題時,看起來你應該尋找一種方法來獲得所有可能的組合。奧利弗馬修斯的答案處理了這個問題的第一部分(找出你可以適應變化的給定類型的硬幣的數量),但是你必須在檢查各種其他組合的循環中這樣做(例如所有便士,所有的鎳幣/便士,所有的硬幣瓦特/便士,所有的區域瓦特/便士等),並需要一種方法來返回組合(例如返回一個結構/類的矢量,通過輸出參數處理硬幣計數 - 是,通過引用的矢量)。