如何在递归函数中计数
how to count in recurrsive function?
本文关键字:递归函数 更新时间:2023-10-16
这是我打印除数的代码,然后打印给定数字的除数数。
现在假设我采用 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
,以使调用者无需在调用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
}
您可以通过
传递计数作为引用来实现这一点 -
#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;
}
-高拉夫
首先,为什么要在全局空间中声明计数变量?
其次,您不能对未声明的变量执行算术运算(在这种情况下,从不声明 int "count")。
第三,为什么要通过做 while(t--) 创建一个无限循环?
您说该函数将所有输入计数为 0,这可能是由于计数从未被宣布吗?
相关文章:
- 递归函数计算序列中的平方和(并输出过程)
- 如何在Elixir中调用递归函数并行
- 递归函数有效,但无法记忆
- 为什么我的递归函数按降序打印,然后按升序打印?
- 为什么递归函数的最终输出是 5?
- 有没有办法使用递归函数找到数组中最小值的 INDEX?C++
- 如何将记忆应用于此递归函数?
- 如何从递归函数中完全返回,该函数给出了每个函数结果的累积相加?
- 无穷大而循环时具有递归函数
- 即使没有调用这个递归函数,它是如何工作的?
- 如何使此递归函数从给定的起始位置返回最小的整数?
- 此递归函数的每次迭代的值存储在哪里?
- 可以清除递归函数中的变量吗?
- 如何在递归函数调用中返回当前函数值
- 递归函数 c++ 的复杂性
- 这个递归函数有什么作用?运行时的复杂性是多少?
- 任何人都可以查明我的递归函数中的错误吗?
- 递归函数的返回类型推导
- 递归函数调用在后台工作
- 查找存储在二叉搜索树的所有非叶子中的数据总和?(返回整数的独立递归函数