2014-01-29 197 views
0

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

回答

1

你错过了一个回报。您应该使用return calculate_gcd(aa, bb, rem, g);而不是仅递归。

你可以使用-Wreturn-type与clang捕捉到这个。其他编译器可能也会对此提出警告。

+0

谢谢。似乎工作。我将递归行更改为“return calculate_gcd(aa,bb,rem,g);” 也让g返回;留。 但为什么?似乎很难想到这个:( – TREMOR

+1

'calculate_gcd'的类型是'int(int aa,int bb,int rem,int g)'这意味着,给定'aa','bb','rem' ,'g',你*承诺*返回一个'int',如果你的函数决定递归,它会调用该函数的一个新的拷贝,但它不会让你失去返回一个整数的承诺。事实上,当你说你会导致未定义的行为时,不会返回一个整数。 – rmcclellan

2

函数头

int calculate_gcd(int aa, int bb, int rem, int g) 

指定g由值通过。

这意味着在一次调用中,将指定的值复制到此函数调用’的本地g。对本地g的更改对呼叫站点没有影响。

相反,你应该return函数的结果,然后你不’吨需要g说法:

int calculate_gcd(int aa, int bb, int rem) 

仔细分析会告诉你,你并不真的需要rem说法要么,所以:

int calculate_gcd(int aa, int bb) 

顺便,作为一个初学者如果使用C++ iostreams(如cout),而不是像printf这样的低级别C I/O函数,将会大大受益。那’因为printf和家人不执行任何类型检查,所以它很容易出错。

此外,虽然这听起来可能只是秃顶,但通过垂直正确排列内容,即使用100%一致的缩进,您将受益匪浅。幸运的是,有免费的工具可以帮助解决这个问题。如果您最喜爱的IDE或编辑器不支持自动源代码格式,请查看免费的AStyle程序。

+0

谢谢,我可能明白这一点,明天我会试试这个,因为在这里睡觉时间,然后选择一个正确答案 – TREMOR

相关问题