该程序如何反向打印?

时间:2016-12-24 08:13:46

标签: c++

输出:123456789987654321 我理解123456789但它的打印方式是987654321

    #include <iostream>

    using namespace std;

    void printNum ( int num )
    {
        cout << num;
        if ( num < 9 )
        {
            printNum ( num + 1 );
        }
        cout << num;
    }

    int main()
    {
        printNum ( 1 );
    }

1 个答案:

答案 0 :(得分:1)

这是调用堆栈

call printNum(1)
1.1 print 1
1.2 call printNum(2)
  1.2.1 print 2
  1.2.2 call printNum(3)
    1.2.2.1 print 3
    ... ... (call printNum to with 4 5 6 7 8 9)
    1.2.2.3 print 3
  1.2.3 print 2
1.3 print 1

查找IDE并逐步运行代码,观察调用堆栈和局部变量。你会明白它是如何运作的。