2012-05-23 19:03:20Morris
[JAVA][作業] Lab8 遞迴
Write a recursive method definition for a static method that has
one parameter n of type int and that returns the nth Fibonacci
number. F0 is 1, F2 is 2, F3 is 3, F4 is 5. And in general Fi+2 =
Fi + Fi+1 for I = 0,1,2,…
Place the method in a class that has a main that tests the method.
真的是非常水...
/**
* @author Shiang-Yun Yang
*/
public class Lab8 {
public static int fibonacciNumber(int n) {
if(n < 2)
return 1;
else
return fibonacciNumber(n-1)+fibonacciNumber(n-2);
}
public static void main(String[] args) {
for(int i = 0; i < 40; i++)
System.out.printf("F(%d) = %d\n", i, fibonacciNumber(i));
}
}
Place the method in a class that has a main that tests the method.
真的是非常水...
/**
* @author Shiang-Yun Yang
*/
public class Lab8 {
public static int fibonacciNumber(int n) {
if(n < 2)
return 1;
else
return fibonacciNumber(n-1)+fibonacciNumber(n-2);
}
public static void main(String[] args) {
for(int i = 0; i < 40; i++)
System.out.printf("F(%d) = %d\n", i, fibonacciNumber(i));
}
}