递归如何工作并打印这些升序降序数字
how recursion works and prints these ascendin descending numbers
代码:
#include <iostream>
using namespace std;
int sub() {
int a;
a=5;
return a;
}
void fact(int x) {
if(x>=1)
{
cout<<"counter:"<<x<<endl;
fact(x-1);
cout<<"after emptying stack"<<x<<endl;
}
cout<<"check"<<endl;
}
int main() {
fact(sub());
}
输出:
counter:3
counter:2
counter:1
check
after emptying stack1
check
after emptying stack2
check
after emptying stack3
check
我已经调试了程序,但是在 if
语句之后,它应该停止并返回到 main
但是在完成后如果它 return 再次返回 cout
并且if
语句终止后程序如何打印数字?请解释(SCREENSHOT)
首先简化您的示例:您的主要功能基本上是调用 fact(5)(因为 sub 总是返回 5)。
下面是对递归调用如何完成的剖析:
-- 5 >= 1 is true --
fact(5):
counter:\n fact(4) after emptying stack 5\ncheck\n
-- 4 >= 1 is true --
fact(4):
counter:\n fact(3) after emptying stack 4\ncheck\n
-- 3 >= 1 is true --
fact(3):
counter:\n fact(2) after emptying stack 3\ncheck\n
-- 2 >= 1 is true --
fact(2):
counter:\n fact(1) after emptying stack 2\ncheck\n
-- 1 >= 1 is true --
fact(1):
counter:\n fact(0) after emptying stack 1\ncheck\n
-- 0 >= 1 is false --
fact(0):
check\n
现在从下到上替换调用:
fact(1):
counter:\n check\n after emptying stack 1\ncheck\n
fact(2):
counter:\n counter:\n check after emptying stack 1\ncheck\n after emptying stack 2\n
fact(3):
counter:\n -- above here -- after emptying stack 3\ncheck\n
...
代码:
#include <iostream>
using namespace std;
int sub() {
int a;
a=5;
return a;
}
void fact(int x) {
if(x>=1)
{
cout<<"counter:"<<x<<endl;
fact(x-1);
cout<<"after emptying stack"<<x<<endl;
}
cout<<"check"<<endl;
}
int main() {
fact(sub());
}
输出:
counter:3
counter:2
counter:1
check
after emptying stack1
check
after emptying stack2
check
after emptying stack3
check
我已经调试了程序,但是在 if
语句之后,它应该停止并返回到 main
但是在完成后如果它 return 再次返回 cout
并且if
语句终止后程序如何打印数字?请解释(SCREENSHOT)
首先简化您的示例:您的主要功能基本上是调用 fact(5)(因为 sub 总是返回 5)。
下面是对递归调用如何完成的剖析:
-- 5 >= 1 is true --
fact(5):
counter:\n fact(4) after emptying stack 5\ncheck\n
-- 4 >= 1 is true --
fact(4):
counter:\n fact(3) after emptying stack 4\ncheck\n
-- 3 >= 1 is true --
fact(3):
counter:\n fact(2) after emptying stack 3\ncheck\n
-- 2 >= 1 is true --
fact(2):
counter:\n fact(1) after emptying stack 2\ncheck\n
-- 1 >= 1 is true --
fact(1):
counter:\n fact(0) after emptying stack 1\ncheck\n
-- 0 >= 1 is false --
fact(0):
check\n
现在从下到上替换调用:
fact(1):
counter:\n check\n after emptying stack 1\ncheck\n
fact(2):
counter:\n counter:\n check after emptying stack 1\ncheck\n after emptying stack 2\n
fact(3):
counter:\n -- above here -- after emptying stack 3\ncheck\n
...