如何撤销递归调用?

时间:2016-10-19 07:04:04

标签: c++ recursion

我的任务是编写一个产生以下输出的函数:

This was written by call number 1.  
This was written by call number 2.  
This was written by call number 3.  
This was written by call number 4.  
This was written by call number 5.  
This was ALSO written by call number 5.  
This was ALSO written by call number 4.  
This was ALSO written by call number 3.  
This was ALSO written by call number 2.  
This was ALSO written by call number 1.

这不仅限于数字5,程序可以接受用户的任何输入,并输出他们的数字。

这是我到目前为止所拥有的:

void function_call(int number);
int main(){
    int userInput;
    cout<<"Please enter a digit: ";
    cin>>userInput;

    function_call(userInput);
}

void function_call(int number){
    if (number == 1){
        cout<<"This was written by call number "<<number<<"."<<endl;
    }

    else{

        function_call(number - 1);
        cout<<"This was written by call number "<<number<<"."<<endl;
    }

}

我当前的代码输出第一部分,但不输出数字减少的第二部分。如何进行输出以显示输出的第二部分?

1 个答案:

答案 0 :(得分:9)

在致电function_call(1,userInput)时尝试此操作:

void function_call(int curr,int last)
{
    if (curr <= last)
    {
        cout<<"This was written by call number "<<curr<<"."<<endl;
        function_call(curr+1,last);
        cout<<"This was ALSO written by call number "<<curr<<"."<<endl;
    }
}