0
鉴于这种方法调用:递归在java中
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);
}
}
我预计:
* fib(i-1) to return 2
* fib(i-2) to return 1
* return 2 + 1 to return 3
结果:
2
这是控制台输出:
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
我明白了一切到这部分:
Into fib with i = 0
何时能拿到我曾经去过0?
ahhhh我看到了,谢谢 – JohnMerlino 2012-07-16 01:42:10
解决它,只需用“return 1”替换语句“return i” – CosmicComputer 2012-07-16 01:54:23
这个函数重现了斐波那契公式,它以0开头,因此它首先返回0。我的问题。 – JohnMerlino 2012-07-16 01:55:56