C ++,递归正确答案但没有正确返回

时间:2014-01-29 20:03:06

标签: c++ recursion return garbage

好的,所以这是我计算最大公约数的简单程序。它每次都和46332964一样返回一个垃圾值。我想了一个小时,但似乎无法理解这个问题。经过研究,我还包括原型但仍然没有运气。它一直有效直到它返回。请复制代码并运行它,请帮助我。

#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 
         }
}

2 个答案:

答案 0 :(得分: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和家人不进行任何类型检查,所以很容易出错。

此外,虽然这听起来像是balderdash,但通过垂直排列,即使用100%一致的缩进,您将获益匪浅。令人高兴的是,有免费的工具可以帮助解决这个问题。如果您喜欢的IDE或编辑器不支持自动源代码格式化,请查看免费的AStyle程序。

答案 1 :(得分:1)

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

你可以使用-Wreturn-type来判断clang。其他编译器可能也会对此发出警告。