3

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

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

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

当我声明int count = 0inside function时,会出现另一个问题factors

对于所有情况,代码都将计数设为 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;
}
4

3 回答 3

1

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

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

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

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
}
于 2013-11-02T18:06:39.213 回答
1

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

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

-高拉夫

于 2013-11-02T18:13:29.770 回答
0

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

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

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

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

于 2013-11-02T18:09:32.610 回答