【问题标题】:Tracing the output, could not figure it out even when debugging it?跟踪输出,调试时也想不通?
【发布时间】:2018-11-20 21:19:24
【问题描述】:

当调用函数 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);
    }

【问题讨论】:

    标签: c++ function output trace


    【解决方案1】:

    f4 函数是递归的。使用 1 或 0 以外的数字进行调用将使其递归。你用 3 调用它,所以编译器(简化)看到

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

    【讨论】:

      【解决方案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。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-05-26
        • 2016-10-15
        • 2011-04-19
        • 2023-03-28
        • 2014-05-23
        • 1970-01-01
        • 1970-01-01
        • 2021-09-28
        相关资源
        最近更新 更多