在嵌套循环的情况下,在多个打印输出的情况下会发生什么?

时间:2017-12-13 11:24:17

标签: java if-statement methods static void

[XDEBUG]
zend_extension = "C:\xampp\php\ext\php_xdebug-2.5.5-7.1-vc14.dll"
xdebug.idekey = netbeans-xdebug
xdebug.profiler_append = 0
xdebug.profiler_enable = 0
xdebug.profiler_enable_trigger = 0
xdebug.profiler_output_dir = "C:/xampp/tmp/xdebug"
xdebug.profiler_output_name = "cachegrind.out.%t-%s"
xdebug.remote_enable = 1
xdebug.remote_autostart = 0
xdebug.remote_connect_back = 0
xdebug.remote_host = "127.0.0.1"
xdebug.remote_port = 9000
xdebug.remote_handler = "dbgp"
xdebug.remote_mode = req
xdebug.remote_log = "C:/xampp/tmp/xdebug/xdebug_remot.log"
xdebug.show_local_vars = 9
xdebug.trace_output_dir = "C:/xampp/tmp"

此代码的输出结果为AAAAA。但我想知道怎么做?我何时考虑public class Test { public static void main(String[] args) { print(4); } static void print(int n){ if (n <= 1) System.out.print("A"); else { print(n-1); print(n-2); } } } 和何时(n-1)

3 个答案:

答案 0 :(得分:1)

首先,问题的标题是错误的。代码中没有循环,只有递归。

现在,要分析输出,让我们看看每种方法的调用:

print(4)
    calls print(3)
        calls print(2)
            calls print(1) which prints 1st A
            calls print(0) which prints 2nd A
        calls print(1) which prints 3rd A
    calls print(2)
        calls print(1) which prints 4th A
        calls print(0) which prints 5th A

共打印"A"个。{/ p>

答案 1 :(得分:0)

你正在做的是递归调用print(int n)方法 - 递归是一种调用自身来解决问题的方法。在数学中,你可以将其表达为f(x)= f(x-1)+ f(x-2)。

print(4) print(3) print(2) print(1) System.out.print("A") print(0) System.out.print("A") print(1) System.out.print("A") print(2) print(1)
System.out.print("A") print(0) System.out.print("A")

您将观察到的是该函数将打印f(n + 2)&#34; A&#34; s,其中f(x)是斐波纳契数列,其中x是大于或等于0的整数

答案 2 :(得分:0)

我希望下图可以帮助您直观显示输出 -

                     print(4)
                     /     \
             print(3)       print(2)
             /   \          /     \
        print(2) print(1) print(1) print(0)
        /   \       |       |       |   
 print(1)  print(0) |       |       |   
    |         |     |       |       |   
    A         A     A       A       A