好吧,所以繼承人我簡單的計算最大的公約數。它每次和46332964一樣返回一個垃圾值。我認爲我的頭一個小時,但似乎無法理解這個問題。經過研究,我還包括原型,但仍然沒有運氣。它工作,直到它返回。請複製代碼並運行它,請幫助我。C++,遞歸正確的答案,但不能正確返回
#include <iostream>
using namespace std;
int calculate_gcd(int aa, int bb, int rem, int g);
int main()
{
int a, b;
int rem = -1;
int gcd=0;
cout << "Number 1: "; //taking inputs
cin >> a;
cout << "Number 2: ";
cin >> b;
if (a < b) //swapping if number greater than the number according to the code
{
a = a + b;
b = a - b;
a = a - b;
}
gcd = calculate_gcd(a, b, rem, gcd);
if (a <= 0 || b <= 0)
{
rem = 0;
cout <<"GCD doesnot exists\n";
} //just in case of zeros
else
cout << "\nthe GCD of "<<a <<" and "<<b <<" is "<<gcd <<"\n\n"; //the main answer
system("pause");
return 0;
}
int calculate_gcd(int aa, int bb, int rem, int g)
{
if (rem != 0)
{
if (aa%bb == 0)
{
rem = 0;
g = bb;
printf("**GCD is %d\n", g);
}
else {
rem = aa % bb;
aa = bb;
bb = rem;
}
calculate_gcd(aa, bb, rem, g);
}
else {
printf("**here also GCD is correct as %d \n", g);
return g; //returning
}
}
謝謝。似乎工作。我將遞歸行更改爲「return calculate_gcd(aa,bb,rem,g);」 也讓g返回;留。 但爲什麼?似乎很難想到這個:( – TREMOR
'calculate_gcd'的類型是'int(int aa,int bb,int rem,int g)'這意味着,給定'aa','bb','rem' ,'g',你*承諾*返回一個'int',如果你的函數決定遞歸,它會調用該函數的一個新的拷貝,但它不會讓你失去返回一個整數的承諾。事實上,當你說你會導致未定義的行爲時,不會返回一個整數。 – rmcclellan