【问题标题】:how to count in recurrsive function?如何计算递归函数?
【发布时间】:2013-11-02 17:54:59
【问题描述】:

这是我打印除数的代码,然后是给定数字的除数。

现在假设我采用 2 个测试用例:5 和 8;此代码将 5 作为 2 和 8 作为 6 的计数(即它添加了先前的计数)。

即使我将其声明为int count = 0;,它也会返回相同的输出。

当我在函数factors 中声明int count = 0 时,会出现另一个问题。

代码将所有情况的计数都设为 0。

#include<iostream>
using namespace std;
int count;
long long factors(long n, long f=1)
{


    if(n%f==0) {
        cout << f << endl;
        count++;
    }

    if(f==n) {
        return 0;
    }

    factors(n,f+1);

    return count;

}

int main()
{
    int n;
    int t;
    cin >> t;
    while(t--)
    {
        cin >> n;
        cout << factors(n) << endl;
    }


    return 0;
}

【问题讨论】:

    标签: c++ recursion factors


    【解决方案1】:

    使用全局变量通常不是一个好主意。它在递归函数中尤其糟糕,最好是可重入的。当然,您可以通过重置循环中的计数来修复您的功能,如下所示:

    while(t--)
    {
        cin>>n;
        count = 0; // Reset count before the recursive call
        cout << factors(n) << endl;
    }
    

    您还可以制作factors“包装器”,重置count,以使调用者无需在调用factors之前重置count,如下所示:

    long long factors(long n) {
        count = 0;
        return factors(n, 1);
    }
    long long factors(long n,long f /* Remove the default */) {
        ... // the rest of your code
    }
    

    【讨论】:

      【解决方案2】:

      您可以通过将计数作为参考来实现这一点 -

      #include<iostream>
      using namespace std;
      
      long long factors(long n, int& count, long f=1)
      {
          if(n%f==0)
          {
              cout<<f<<endl;
              count = count + 1;
          }
      
          if(f==n)
            return 0;
      
          factors(n, count, f+1); 
          return 0;
      }
      
      int main()
      {
          int n,t;
          cin>>t;
          while(t--)
          {
                  cin>>n;
                  int count = 0;
                  factors(n, count);
                  cout << count << endl;
          }
          return 0;
      }
      

      -高拉夫

      【讨论】:

        【解决方案3】:

        首先,为什么要在全局空间中声明 count 变量?

        其次,您不能对未声明的变量执行算术运算(在这种情况下,从未声明过 int "count")。

        三、为什么要通过while(t--)创建无限循环?

        您说该函数将所有输入的计数设为 0, 这可能是因为 count 从未被宣布吗?

        【讨论】:

        • 我认为在这种形式下,您的帖子并不能真正成为答案。你提出的问题比OP还多!如果这不是一个答案,您必须赢得一些声誉才能有资格发布您可以在其中提出更多问题的 cmets。
        • Alex,请记住我们的格式是一种涉及问答的格式。您的问题似乎更具修辞性,但为了消除混淆,我强烈建议您进行编辑以说出您的意思。例如,您在全局命名空间中声明的原因可以编辑为“您不应该在全局命名空间中声明计数”。祝你好运,希望这能帮到你! :)
        猜你喜欢
        • 1970-01-01
        • 2013-11-26
        • 2015-07-28
        • 2021-05-03
        • 2023-02-04
        • 1970-01-01
        • 1970-01-01
        • 2022-11-25
        • 2021-02-24
        相关资源
        最近更新 更多