2012-07-16 103 views
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?

回答

5

fib(3)來電fib(2)。當您撥打fib(2)時,它將撥打fib(i-1)fib(i-2),即fib(1)fib(0)

+0

ahhhh我看到了,謝謝 – JohnMerlino 2012-07-16 01:42:10

+0

解決它,只需用「return 1」替換語句「return i」 – CosmicComputer 2012-07-16 01:54:23

+0

這個函數重現了斐波那契公式,它以0開頭,因此它首先返回0。我的問題。 – JohnMerlino 2012-07-16 01:55:56