1

プログラミングのクラスで課題があり、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;
    }
}

ここでの問題は、プログラムを実行すると、4 分の 1、1 セント硬貨、および 5 セント硬貨に対して非常に大きな負の値が返されることです。ループ条件の設定方法に関係があると確信していますが、なぜこれが起こっているのか誰にも分かりますか?

4

2 に答える 2

2

2 つの問題: 1 つの未定義のコインの初期値。二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大量のものに使用する方がよいことに注意してください。

于 2013-10-07T15:05:12.030 に答える