2014-10-26 64 views
-5

我在寫兩個程序。一個數字提高到另一個數字的能力,另一個數字的最大公約數。他們都使用無限遞歸崩潰,我不知道爲什麼。有人可以看看這些並給我建議嗎?請不要發佈完整的解決方案,只有建議。兩個程序中的無限遞歸

#include <iostream> 
using namespace std; 
int pow(int base, int exp) { 
int somevariable = pow(base,exp-1); 
if (base == 0) { 
     return 1; 
} 
else { 
     return base * pow (base,exp-1); 
     } 
} 
int main () { 
int base; 
int power; 
cout << "This program calculates exponential values." << endl; 
cout << "Enter the base: "; 
cin >> base; 
cout << "Enter the power: "; 
cin >> power; 
cout << "" << endl; 
cout << base << "^" << power << " =" << 
cout << pow(base, power); 
} 
#include <iostream> 
using namespace std; 
int gcd(int number1, int number2) { 
int returnj = 0; 
if(number1 || number2 >= 0) { 
      return gcd(number2, number1 % number2); 
      } 

      else if(number1 || number2 == 0) { 
       return 1; 
       } 
} 
int main () { 
int number; 
int another; 
int gcdd; 
cout << "This program calculates the greatest common divisor (GCD) for two integers." << endl; 
cout << "Enter a number: "; 
cin >> number; 
cout << "Enter another: "; 
cin >> another; 
cout << "" << endl; 
cout << "GCD = " << gcd(number, another); 

}

+0

爲什麼你檢查'base'等於零?學習使用調試器,並通過你的代碼看看發生了什麼。在第二個...... C++不是英語,邏輯操作不像你認爲的那樣工作。 – luk32 2014-10-26 20:57:29

+0

我檢查基地等於零,因爲我想返回1如果基地是0,而不是正常的遞歸調用。 – Kelton2 2014-10-26 21:00:04

+0

您的'pow'函數包含無條件遞歸調用。它無法停止遞歸。 – RocketR 2014-10-26 21:00:33

回答

0

戰俘功能,您需要更改

if (base == 0) 

要:

if (exp == 0) 

然後,它會不會是無限遞歸。

+0

仍然無法正常工作。 – Kelton2 2014-10-26 21:08:50

+0

這不會解決問題,因爲在'pow'開始時立即調用'pow'。所以這個'如果'甚至沒有達到過。 – RocketR 2014-10-26 21:09:42

+0

我修復了崩潰 - 但現在結果是垃圾,另一個程序仍然被破壞。 – Kelton2 2014-10-26 21:11:56

0

現就職於

#include <iostream> 
using namespace std; 

int pow(int base, int exp) { 
    //There's was a line here creating a loop because it never arrives to a return 
    if (exp == 0) { // base 0 makes not sense because the base it's always the same, it's the exp that decreases 
      return 1; 
    } 
    else { 
      return base * pow (base,exp-1); 
    } 
} 

int main () { 
    int base; 
    int power; 
    cout << "This program calculates exponential values." << endl; 
    cout << "Enter the base: "; 
    cin >> base; 
    cout << "Enter the power: "; 
    cin >> power; 
    cout << "" << endl; 
    cout << base << "^" << power << " = "; // This line was not closed. 
    cout << pow(base, power); 
}