[英]How does this recursive method print 3 times instead of just exiting?
public static void foo(int n) {
if(n > 0) {
if(n % 2 == 0) {
foo(n - 3);
} else {
foo(n - 1);
}
}
System.out.println(n);
}
I'm not understanding the recursive method here. 我在这里不了解递归方法。 I see how it would print -1, but I'm not understanding how it would print "-1 2 3".
我知道它将如何显示-1,但是我不明白它将如何显示“ -1 2 3”。 Any help would be appreciated.
任何帮助,将不胜感激。
The method was called by foo(3)
该方法由
foo(3)
调用
This is the process.. 这是过程。
foo(3) --> foo(2)
//because (3 % 2 != 0)
foo(2) --> foo(-1)
//because (2 % 2 == 0)
foo(-1) --> print -1
//because (-1 < 0)
//goes back & continue from last point where this method is called
print 2, then exit method
//goes back & continue from last point where this method is called
print 3, then exit method
//goes back & continue from last point where this method is called
back to main()
I did, I used pythontutor.com to visualize it, but I don't get why after it prints -1, it goes back to the "n % 2" line
我做到了,我使用pythontutor.com对其进行了可视化,但是我不明白为什么它在打印-1之后返回“ n%2”行
It still continue to prints because after printing -1
, even though it exits the method which prints -1, but it returns and continue from where foo(-1) was called. 它仍然继续打印,因为在打印
-1
,即使它退出了打印-1的方法,但它仍返回并从调用foo(-1)的位置继续。 It continues from there.. 它从那里继续。
Recursive method are working continuesly by requesting same methods it self. 递归方法通过自身请求相同的方法而继续工作。 In your Code when you request
foo (3);
在您的代码中,当您请求
foo (3);
Time 1 : 3%2=1
so this will request ELSE
part Then foo (3-1)
= foo (2);
时间1:
3%2=1
因此这将要求ELSE
部分然后foo (3-1)
= foo (2);
will be called. 将被称为。 Time 2 :
2%2=0
so this will request IF
part Then foo (2-3)
= foo (-1)
will be called. 时间2:
2%2=0
因此这将请求IF
部分,然后将调用foo (2-3)
= foo (-1)
。 Time 3 : -1 > 0 = False
So Print Method will be called. 时间3:
-1 > 0 = False
因此将调用Print Method。
System will print -1
. 系统将打印
-1
。 Time 3 function will be ended and goes to Time 2 function 时间3功能将结束并进入时间2功能
System will print 2
Time 2 function will be ended and goes to Time 1 function 系统将打印
2
时间2功能将结束并进入时间1功能
System will print 3
. 系统将打印
3
。
So the output -1 2 3
所以输出
-1 2 3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.