gpt4 book ai didi

c++ - 如何计算递归函数?

转载 作者:太空狗 更新时间:2023-10-29 21:44:34 24 4
gpt4 key购买 nike

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

现在假设我有 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;
}

最佳答案

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

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

您还可以制作 factors 重置 count 的“包装器”,以使调用者无需在调用 之前重置 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
}

关于c++ - 如何计算递归函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19744953/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com