C++ 函数的递归 [英] Recursion with functions in C++

查看:53
本文介绍了C++ 函数的递归的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法理解这段代码:

#include <iostream>
using namespace std;

void Print_numm(int numm){
    cout<<numm;
    if (numm<=4) {
        Print_numm(numm+1);
    }
    cout<<numm;
}


int main() {
    Print_numm(1);
    return 0;
}

输出为 1234554321.我理解递归直到它打印 123455.但是为什么编译器将其余的数字打印为 1?编译器是否每次都执行第二次cout"?如果是这样,它如何保持数字直到它们打印到 5,然后向下打印其余部分?

The output is 1234554321. I understand the recursion up until it prints 123455. But why the compiler prints the rest of of numbers down to 1? Does the compiler do the second "cout" every time? And if so how it keeps the numbers until they are printed up to 5 and then prints the rest downward?

推荐答案

您熟悉堆栈吗?

函数调用自身,向上打印每个数字,然后从最后的递归调用返回,向下遍历数字,因为它重复从递归返回.它只执行递归之后包含的其余代码打电话.

The function calls itself,and prints every number upwards,then it returns from the final recursive call,going downwards through the numbers,as it return from recursion repeatedly.It just executes the rest of the code that it contains after the recursive call.

一个简单的表示是:

    print_numm(1):
    cout << 1
    print_numm(1+1):
        cout << 2
        print_numm(2+1):
            cout << 3
            print_numm(3+1):
                cout << 4
                print_numm(4+1):
                    cout << 5
//now the number is bigger than 4 so the function
//will return from recursion
                    cout << 5
//now the function is done,but the function that called print_numm(5) is waiting to finish
//so it executes the rest of the code printing 4,same with all waiting for print_numm(4) and so on
                cout << 4
            cout << 3
        cout << 2
    cout << 1

这篇关于C++ 函数的递归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆