所以,我創建了一個硬幣更改算法,採用值N和任何數量的面額,如果它沒有1,我必須自動包括1。我已經這樣做了,但現在有一個缺陷,我有2個矩陣,我需要使用其中的1個。是否有可能重寫S [i]矩陣,並且仍然增加數組的大小......另外,我怎樣才能找到最大面額和第二高和sooo直到最小?我應該把它從高到低排列,以便讓它變得更容易,或者有更簡單的方法來一個接一個地尋找它們嗎?貪婪算法硬幣更換C++
int main()
{
int N,coin;
bool hasOne;
cout << "Enter the value N to produce: " << endl;
cin >> N;
cout << "Enter number of different coins: " << endl;
cin >> coin;
int *S = new int[coin];
cout << "Enter the denominations to use with a space after it" << endl;
cout << "(1 will be added if necessary): " << endl;
for(int i = 0; i < coin; i++)
{
cin >> S[i];
if(S[i] == 1)
{
hasOne = true;
}
cout << S[i] << " ";
}
cout << endl;
if(!hasOne)
{
int *newS = new int[coin];
for(int i = 0; i < coin; i++)
{
newS[i] = S[i];
newS[coin-1] = 1;
cout << newS[i] << " ";
}
cout << endl;
cout << "1 has been included" << endl;
}
//system("PAUSE");
return 0;
}
我會建議只是其中分類到你所需要的順序。我不確定爲什麼你加1,如果「必要」 - 對於沒有硬幣值爲1的貨幣呢?例如,從1950年到2000年,[里拉硬幣](https://en.wikipedia.org/wiki/Coins_of_the_Italian_lira)正在使用,即使有的話,仍然有1個里拉硬幣仍在流通。 –
是的,但我們不想要這裏的情況33我們不能得到它,因爲沒有1,所以這是必要的 – Darkflame
如果用戶輸入無意義的輸入,你應該告訴他們。你無法知道錯誤是否輸入了33個金幣或者不包括1個硬幣。無論是否需要,您都要加1。 –