package homework;
public class FibonacciSequence {
public static void main(String[] args) {
int fiponatch[] = new int[15];
/**
* 方法一
*/
fiponatch[0] = 1;
fiponatch[1] = 1;
System.out.println("方法一输出斐波那契数列:");
for (int i = 0; i < fiponatch.length; i++) {
if (i > 1) {
fiponatch[i] = fiponatch[i - 2] + fiponatch[i - 1];
}
System.out.print(fiponatch[i] + " ");
}
/**
* 方法二
*/
System.out.println("\n\n方法二输出斐波那契数列:");
for (int i = 1; i < fiponatch.length + 1; i++) {
System.out.print(FibonacciSequence(i) + " ");
}
}
private static int FibonacciSequence(int i) {
if (i == 1 || i == 2) {
return 1;
} else {
return FibonacciSequence(i - 2) + FibonacciSequence(i - 1);
}
}
}
Java两种方式打印斐波那契数列
最新推荐文章于 2024-02-25 10:33:50 发布