//amt = amount of cents to get change for
//onhand = array of available coins . Ex: {3, 0, 1, 0} = 3 quart, 0 dime, 1 nickel, 0 pennies
//denoms = {25, 10, 5, 1}
//ndenoms = 4 ; i.e the number of different denominations
// thechange = array of change. Ex: if amt = 80, then one possible thechange = {3, 0, 1, 0} b/c 3*25 + 1*5 = 80 cents
int i = 0;
void makechange(int amt, int *onhand, int *denoms, int ndenoms, int *thechange)
{
if ((denoms[i] * onhand[i]) > amt)
{
onhand[i]--; // # of coins is too much, decrement and try again
makechange(amt, onhand, denoms, ndenoms, thechange); // try agan
}
thechange[i] = onhand[i]; //found #of coins
amt = amt - denoms[i]*onhand[i]; // get remaining amount from change
i++;
if (amt != 0) // we're not done with change so move on to next denomination
{
makechange(amt, onhand, denoms, ndenoms, thechange);
}
else if (amt == 0) // we're done with the change so all the other # coins = 0
{
for (int j = i; j < amt; j++)
{
thechange[j] = 0;
}
}
}
Now, down in main when I actually call the function prototype and print out the result
//
makechange(amt, onhand, denoms, ndenoms, thechange);
for (int k = 0; k < ndenoms; k++)
{
cout << thechange[i] << " ";
}
//
私はエラーが発生します。再帰メソッドがクラッシュする(アルゴリズム変更)
このアルゴリズムは私には分かりやすいようですが、誰でもなぜクラッシュするのか知っていますか?
再帰を正しく使用しましたか?
どのようにクラッシュしますか?それが起こるとエラーが出ますか?これはどんな言葉ですか? – Blender
あなたはどんなエラーを受けていますか? – Femaref
私はC++を使用しており、devC++でコンパイルしています –