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?
fib(3)
calls fib(2)
. When you call fib(2)
, it will call fib(i-1)
and fib(i-2)
, that is, fib(1)
and fib(0)
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.