c++ - 为什么这个函数按升序打印 1 2 3 4 5
问题描述
我尝试搜索答案,但无法得到任何令人信服的答案。有人可以解释一下这个 c++ 代码是如何打印的1 2 3 4 5
吗?
直到n=1
. 什么时候n=1
,因为不满足fun(n-1) = fun(1-1) = fun(0)
而没有执行,因此现在将被执行并且仍然等于但是在打印之后它应该停止?它如何转到以前的电话?它是如何打印的?n>0
cout << n << endl
n
1
1
2 3 4 5
当它在cout << n << endl
上面fun(n-1)
打印时也是有意义的5 4 3 2 1
。
#include <iostream>
using namespace std;
void fun(int n)
{
if (n > 0) {
fun(n - 1);
cout << n << endl;
}
}
int main()
{
int x = 5;
fun(x);
}
上面的代码打印1 2 3 4 5
,而据我了解,它应该只打印1
。
解决方案
在每次调用函数时fun()
,记下变量的值n
,您可以轻松地跟踪输出。当递归调用fun()
return时,它后面的语句都会被执行(wrt function fun()
it is cout << n << endl;
statement)。它是这样工作的:
fun(5) --> First call : n is 5
5>0 : true
| fun(5-1) --> Recursive call 1 : n is 4
| 4>0 : true
| | fun(4-1) --> Recursive call 2 : n is 3
| | 3>0 : true
| | | fun(3-1) --> Recursive call 3 : n is 2
| | | 2>0 : true
| | | | fun(2-1) --> Recursive call 4 : n is 1
| | | | 1>0 : true
| | | | | fun(1-1) --> Recursive call 5 : n is 0
| | | | | 0>0 : false --> Return from call 5
| | | | |
| | | | Print n (n is 1) and return from call 4
| | | Print n (n is 2) and return from call 3
| | Print n (n is 3) and return from call 2
| Print n (n is 4) and return from call 1
Print n (n is 5) and return from first call to main()
因此,输出为1 2 3 4 5
。
推荐阅读
- algorithm - 最坏情况最小排序时间复杂度定理
- angular6 - 当组件在 Angular 应用程序内部使用并作为 Angular 之外的自定义元素时出现 Angular 元素错误
- javascript - 如何从 args 中提取数据和文件名以上传文件?
- java - Java 中的多线程与 Task 仅在 onClick Button 时工作一次
- jenkins - 为动态创建的 gitlab 存储库部署 jenkins 作业
- javascript - JS中只接收一个参数
- java - Android自定义对话框进入ConstraintLayout中的视图
- spring-mvc - 如何使用 MockMvc 解决 MethodArgumentConversionNotSupportedException?
- mysql - 如何将 .txt 文件导入数据库?
- replace - 在 MS Word 中使用通配符替换特殊字符并重新格式化文本