繁体   English   中英

如何从此代码中获取递归调用的数量?

[英]how do i get numbers of recursive calls from this code?

using namespace std;
static int count = 0;
int f(int n, int& count)
{
    count++;
    if (n == 0 || n == 1) return n;
    else
        return f(n - 1, count) + f(n - 2, count);
}
int main()
{
    int n = 7;
    int count = 0;
    cout << f(n, count) << " " << count;
}

计数的 output 为 0,我不知道为什么。 我的意图是知道递归调用的号码

<< 之前的东西是 C 出来的。 如果我将它们连接在一起,我将无法发布该内容

 cout << f(n, count) << " " << count;

您可能希望先评估fn(n, count)然后再评估count ,但如果您使用的 C++ 版本早于 C++17 ,则评估顺序未指定 <<不是序列点 编译器可以自由评估count first 或fn(n, count) 因此,您得到的 output,即首先评估count

您可以做的是引入这样的序列点:

cout << f(n, count);  //semicolon is a sequence point
cout << " " << count;

你应该得到你期待的 output。 此外,由于count是通过引用传递的,因此根本不需要 static 变量。

在您的代码中,您不需要使用static int count=0 ,因为您将引用传递给main中声明的变量count ,但它仍然不会更改 output。 以下代码适用于 gcc 编译器。 我觉得另一位用户的评论更正了问题可能出在 C++ 版本上。

#include <iostream>
using namespace std;
int f(int n, int& count)
{
    count++;
    if (n == 0 || n == 1) return n;
    else
        return f(n - 1, count) + f(n - 2, count);
}
int main()
{
    int n = 7;
    int count = 0;
    cout<<f(n, count)<<" "<< count;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM