[英]recursion in java
Given this method call: 给定此方法调用:
public class MainClass {
public static void main(String[] args) {
System.out.println(fib(3));
}
private static int fib(int i) {
System.out.println("Into fib with i = " + i);
if (i < 2) {
System.out.println("We got here");
return i;
}
return fib(i-1) + fib(i-2);
}
}
I expected: 我期望:
* fib(i-1) to return 2
* fib(i-2) to return 1
* return 2 + 1 to return 3
Result: 结果:
2
This is the output of console: 这是控制台的输出:
Into fib with i = 3
Into fib with i = 2
Into fib with i = 1
We got here
Into fib with i = 0
We got here
I understand everything up to this part: 我了解到这部分的一切:
Into fib with i = 0
When could have i ever been 0? 我什么时候可以成为0?
fib(3)
calls fib(2)
. fib(3)
调用fib(2)
。 When you call fib(2)
, it will call fib(i-1)
and fib(i-2)
, that is, fib(1)
and fib(0)
. 调用
fib(2)
,它将调用fib(i-1)
和fib(i-2)
,即fib(1)
和fib(0)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.