gpt4 book ai didi

c++ - 如何反转递归调用?

转载 作者:太空狗 更新时间:2023-10-29 19:57:09 26 4
gpt4 key购买 nike

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

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;
}

}

我当前的代码输出第一部分,但不输出数字正在减少的第二部分。如何才能显示输出的第二部分?

最佳答案

在调用 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;
}
}

关于c++ - 如何反转递归调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40124404/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com