跟踪输出,即使调试也无法弄清楚?

时间:2018-11-20 21:19:24

标签: c++ function output tracing

调用函数f4时,函数如何返回6?我真的不知道该函数如何运行,不应该返回1?由于(n-1)

  #include <iostream>
    #include<cmath>
    #include<fstream>
    using namespace std;
    int x = 3;
    void f1(int, int &);

    int f4(int);

    int main()

    { 
        int x = 5; int y = 10;
        f1(x, y); 
        cout << x << "\t" << y << endl;
        x = 15; y = 20;
        f1(x++, x); 


        cout << x << "\t" << y << endl; 
        x = 3;
        cout << f4(x) << endl; 

        system("pause");
        return 0;
    }

    void f1(int a, int &b)
    {
        a *= 2; b += x;
        cout << a << "\t" << b << endl;
    }

    int f4(int n) {
        if (n == 1 || n == 0) 
            return n;
        else
            return n + f4(n - 1);
    }

2 个答案:

答案 0 :(得分:2)

f4函数是递归的。使用非1或0的数字进行此调用将使其递归。您用3来调用它,所以编译器(简体)看到了

f4(3) => 3 + f4(2) => 3 + 2 + f4(1) => 3 + 2 + 1 => 5 + 1 => 6

答案 1 :(得分:2)

简而言之递归。

   int f4(int n) {
        if (n == 1 || n == 0) 
            return n;
        else
            return n + f4(n - 1);
 }

您的代码指出,当n为1或0时,仅返回n,否则将n添加到函数的结果中。

建立一个递归堆栈,其中第一个调用n = 3并递归。 在下一个调用中,n = 2,并且递归。 在下一次调用n = 1时,它返回,以及堆栈的其余部分导致1 + 2 + 3(即6)。