我正在計算總和為 N 的最少 3 和 5。我使用了記憶和遞回演算法。
問題是,當我運行程式并輸入 11 時,temp3 = calculate(8) 回傳 1,而它應該清楚地回傳 2。
我已經檢查過在呼叫 calculate(8) 之前, arr[8] = 2 已經。
#include <iostream>
using namespace std;
int init, N, temp3, temp5;
int arr[5001];
int calculate(int N) {
if(arr[N]==0){
temp3 = calculate(N-3);
temp5 = calculate(N-5);
if (temp3!=-1 && temp5!=-1){
if (temp3<=temp5) {
arr[N] = temp3 1;
}
else {
arr[N] = temp5 1;
}
}
else if (temp5!=-1) {
arr[N] = temp5 1;
}
else if (temp3 != -1) {
arr[N] = temp3 1;
}
else {
arr[N] = -1;
}
}
return arr[N];
}
int main()
{
arr[1]=-1;arr[2]=-1;arr[3]=1;arr[4]=-1;arr[5]=1;
cin >> init;
cout << calculate(init);
return 0;
}
uj5u.com熱心網友回復:
您正在對全域變數進行操作!幾個遞回呼叫使用相同的變數,并且呼叫會temp5 = calculate(N-5);覆寫temp3先前由呼叫設定的值temp3 = calculate(N-3);!
解決方案:不要使用全域變數!
int temp3 = calculate(N-3);
int temp5 = calculate(N-5);
這樣,每個遞回呼叫都有自己的一組變數,并且不會覆寫存盤在另一個遞回呼叫中的值。
一般來說:如果你真的,真的需要一個全域變數,請始終考慮。雖然有時它們無法避免(沒有不合理的努力),但它們通常只是邪惡的根源!
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/495656.html
下一篇:有人可以解釋一下這個遞回嗎?
