首页 > 解决方案 > 为什么这个函数按升序打印 1 2 3 4 5

问题描述

我尝试搜索答案,但无法得到任何令人信服的答案。有人可以解释一下这个 c++ 代码是如何打印的1 2 3 4 5吗?

直到n=1. 什么时候n=1,因为不满足fun(n-1) = fun(1-1) = fun(0)而没有执行,因此现在将被执行并且仍然等于但是在打印之后它应该停止?它如何转到以前的电话?它是如何打印的?n>0cout << n << endln112 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

标签: c++recursion

解决方案


在每次调用函数时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


推荐阅读