如何在递归函数中仅调用一次函数?

时间:2018-07-23 15:18:19

标签: c++ function recursion static

我只想调用一次递归函数。我像对静态变量一样尝试了它,但是它引发了错误。有人可以提出解决方案吗?

说我有功能recur(int j)

void recur(int x){
    if(x==0)
        return;
    //want x to be xth fibnocci number,but only at initialization.
    x=fib(x);
    cout<<x<<" ";
    recur(x-1);
}

recur(5)的输出应该是{5,4,3,2,1},而不是{5,3,1}我只想在函数内部做。

2 个答案:

答案 0 :(得分:0)

每当您希望变量以某种方式在函数中启动时(无论是否递归),都应通过函数参数进行处理。该功能已经设置为具有初始化阶段。

示例:

void recur(int x){
    if(x==0)
        return;
    cout<<x<<" ";
    recur(x-1);
}

int main() {
    recur(fib(x));
    return 0;
 }

答案 1 :(得分:0)

我们可以使用静态布尔标志变量来存储是否计算斐波那契数。在基本情况下,可以将该标志设置为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;
}

第二个版本:

#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;
}
相关问题