无法理解递归 [英] Trouble Understanding Recursion

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

问题描述

好的,我有一个程序:

public class Rec {
    public static void main(String[] args) {
        test(5);
    }
    static void test(int n) {
        if (n > 0) {
        System.out.println(n);
        test(n-1);
        System.out.println(n);
        }
    }

它的输出是 5,4,3,2,1,1,2,3,4,5.我的问题是,为什么/如何执行第二个 println(n) 语句?我认为函数调用会完全切断它,相反它的行为让我感到困惑.这不是家庭作业或其他任何东西,我真的很难理解递归的工作原理.

It's output is 5,4,3,2,1,1,2,3,4,5. My question is, why/how does the second println(n) statement get executed? I thought that the function call would completely cut it off, instead it acted in a way that baffles me. This isn't homework or anything, I just really am having a hard time understanding how recursion works.

推荐答案

所有方法调用完成后都返回同一个地方.

All method calls return to the same place once they are done.

通过有效地将它们链接起来

By effectively chaining them you get

 System.out.println(5)
     System.out.println(4)
        System.out.println(3)
            System.out.println(2)
                system.out.println(1)
                   // If is not true now.
                System.out.println(1)
            System.out.println(2)
        System.out.println(3)
     System.out.println(4)
 System.out.println(5)

有意义吗?

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

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