无穷大而循环时具有递归函数

infinity while loop when have recursive function

本文关键字:递归函数 循环 无穷大      更新时间:2023-10-16

我正在解决一个问题。我想要一个函数,它返回所有方法,使不同的正数int加上等于该数字,例如 6 将是 1+5 ,2+3+1,2+4 所以将是 3 但我的解决方案返回无限循环

#include <iostream>
using namespace std;
int find(int num,int before)
{
int first=1;
int count=1;
int end =num-1;
if(end-first==0) return count;
while(end-first!=1&&end-first!=0)
{
if(end==before||first==before) continue;
first++;
end--;
}
before=first;
return count+find(end,before);
}
int main()
{
int a;
cin>>a;
int x=find(a,1);
cout<<x;
}

我尝试循环cout"a"并永远重复。请帮助我。

编辑:我的代码只是解决了一块问题,所以它不是解决方案,我会尝试关闭主题,谢谢大家

在这个概念中,first将始终为 1,before将始终为1,因为此处first永远不会递增,因为未达到指令。

first1初始化,before1初始化,这意味着before==first为 true,循环将在continue后忽略所有其他指令。

既然你比较end==before||first==before这永远是正确的,因为即使end==beforefalse第二个测试也是真的。false||true的测试逻辑是true