此递归函数如何到达此输出? [英] How does this recursive function get to this output?

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

问题描述

当我将这段代码运行为n = 5时,我得到的输出是"5 3 1 1 3 5"我得到5 3 1部分,但是在那之后n = -1,但是当我用调试器运行代码时,当n = -1时它会转到 numbers(n-2); ie之后的行 System.out.prt(n +"); ,即使该语句包含在if块中.

When I run this piece of code for n=5 the output I get is "5 3 1 1 3 5" I get the 5 3 1 part but after that n=-1 but when I run the code with a debugger it when n=-1 it goes to the line after numbers(n-2);i.e System.out.prt(n+ ""); even though that statement is contained in the if block.

为什么会这样?

public void numbers(int n)
{
    if(n>0)
    {
        System.out.print(n+" ");
        numbers(n-2);
        System.out.print(n+" ");
    }
}

TLDR:当n = -1 System.out.prt(n +"); 时,即使它位于if块中,而if块仅在n> 0时运行.

TLDR : when n=-1 System.out.prt(n+ "");even though it is within the if block which only runs when n>0.

任何帮助将不胜感激.提前致谢!

Any help would be much appreciated. Thanks in advance!

推荐答案

对于 n == 5 :

numbers(5);
    if(5 > 0)--> true : 
        System.out.print(5 + " "); // (1)
        numbers(3);
        |   if(3 > 0)--> true : 
        |       System.out.print(3 + " "); // (2)
        |       numbers(1);
        |       |   if(1 > 0)--> true : 
        |       |       System.out.print(1 + " "); // (3)
        |       |       numbers(-1);
        |       |       System.out.print(1 + " "); // (4)
        |       System.out.print(3 + " "); // (5)
        System.out.print(5 + " "); // (6)

注意每个数字应该如何打印两次:

Notice how each number is supposed to be printed twice:

System.out.print(n + " "); // print once
numbers(n-2);
System.out.print(n + " "); // print twice

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

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