好吧,所以继承人我简单的计算最大的公约数。它每次和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