题目要求:编写程序在控制台输出斐波那契数列前20项,每输出5个数换行
//其一方法:
public class Demo2 { public static void main(String[] args) { int a = 1 , b = 1 , c = 0 ; System.out.println("斐波那契数列前20项为:" ); System.out.print(a + "\t" + b + "\t" ); for ( int i = 1 ; i <= 18 ; i++) { c = a + b; a = b; b = c; System.out.print(c + "\t" ); if ((i + 2 ) % 5 == 0 ) System.out.println(); } } }
//java编程:三种方法实现斐波那契数列
//其二方法:
public class Demo3 { public static void main(String[] args) { int arr[] = new int [ 20 ]; arr[0 ] = arr[ 1 ] = 1 ; for ( int i = 2 ; i < arr.length; i++) { arr[i] = arr[i - 1 ] + arr[i - 2 ]; } System.out.println("斐波那契数列的前20项如下所示:" ); for ( int i = 0 ; i < arr.length; i++) { if (i % 5 == 0 ) System.out.println(); System.out.print(arr[i] + "\t" ); } } }
//java编程:三种方法实现斐波那契数列
//其三方法:
public class Demo4 { private static int getFibo( int i) { if (i == 1 || i == 2 ) return 1 ; else return getFibo(i - 1 ) + getFibo(i - 2 ); } public static void main(String[] args) { System.out.println("斐波那契数列的前20项为:" ); for ( int j = 1 ; j <= 20 ; j++) { System.out.print(getFibo(j) + "\t" ); if (j % 5 == 0 ) System.out.println(); } } }
兔子题的实质就是斐波那契数列:
有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子总数为多少?
public class Test { public int Fibonacci(int i) { if (i == 1 || i == 2) { return 1; } else { return Fibonacci(i - 1) + Fibonacci(i - 2); } } public static void main(String[] args) { Test test = new Test(); int n = 12; for (int i = 1; i <= n; i++) { int fibonacci = test.Fibonacci(i); System.out.println(fibonacci); } } }