C++ 如何在递归函数中只调用一次函数?
我只想调用递归函数一次。我像对待静态变量一样尝试了它,但它抛出了一个错误。有人能提出解决办法吗 假设我有函数C++ 如何在递归函数中只调用一次函数?,c++,function,recursion,static,C++,Function,Recursion,Static,我只想调用递归函数一次。我像对待静态变量一样尝试了它,但它抛出了一个错误。有人能提出解决办法吗 假设我有函数recur(int j): void recur(int x){ 如果(x==0) 返回; //希望x是第x个fibnocci编号,但仅在初始化时。 x=fib(x); cout任何时候,当你想让一个变量在函数中以某种方式启动时(无论它是递归的还是非递归的),你都应该通过函数参数来处理它。函数已经设置为有一个初始化阶段 例如: void recur(int x){ if(x==0)
recur(int j)
:
void recur(int x){
如果(x==0)
返回;
//希望x是第x个fibnocci编号,但仅在初始化时。
x=fib(x);
cout任何时候,当你想让一个变量在函数中以某种方式启动时(无论它是递归的还是非递归的),你都应该通过函数参数来处理它。函数已经设置为有一个初始化阶段
例如:
void recur(int x){
if(x==0)
return;
cout<<x<<" ";
recur(x-1);
}
int main() {
recur(fib(x));
return 0;
}
void recur(int x){
如果(x==0)
返回;
cout我们可以使用一个静态布尔标志变量来存储我们是否计算了斐波那契数。该标志可以在基本情况下设置为false,这样就不会影响将来的调用。还有其他方法可以取消设置该标志,例如使用该标志来确定函数是否第一次被调用,以及在调用后取消设置该标志递归调用
#include <iostream>
void recur(int x)
{
static bool flag = false;
if(x==0)
{
flag = false; //this happens near the end of the recursive calls
return; //so we can unset the flag here
}
if(!flag)
{
x = fib(x);
flag = true;
}
std::cout<<x<<" ";
recur(x-1);
}
int main()
{
recur(3);
std::cout << '\n';
recur(5);
std::cout << '\n';
return 0;
}
#包括
无效重现(整数x)
{
静态布尔标志=假;
如果(x==0)
{
flag=false;//这发生在递归调用的末尾附近
return;//因此我们可以在这里取消设置标志
}
如果(!标志)
{
x=fib(x);
flag=true;
}
std::coutWhy不将fib(x)
传递到函数中,如recur(fib(x))
?这就是变量的起始值应该存在的地方注释掉这一行x=fib(x);
#include <iostream>
void recur(int x)
{
static bool flag = false;
if(x==0)
{
flag = false; //this happens near the end of the recursive calls
return; //so we can unset the flag here
}
if(!flag)
{
x = fib(x);
flag = true;
}
std::cout<<x<<" ";
recur(x-1);
}
int main()
{
recur(3);
std::cout << '\n';
recur(5);
std::cout << '\n';
return 0;
}
#include <iostream>
void recur(int x)
{
static bool flag = false;
if(x==0)
{
return;
}
bool otherFlag = false;
if(!flag)
{
x = fib(x);
flag = true;
otherFlag = true;
}
std::cout<<x<<" ";
recur(x-1);
if(otherFlag)
{
flag = false;
}
}
int main()
{
recur(3);
std::cout << '\n';
recur(5);
std::cout << '\n';
return 0;
}