Java生成斐波那契数列(0,1,1,2,3,5,8,13,21,……):while循环,for循环分别实现
时间: 2024-09-20 17:06:59 浏览: 50
在Java中,我们可以使用while循环和for循环来生成斐波那契数列。下面我会分别给出两个实现方法。
**While循环实现:**
```java
public class Fibonacci {
public static void main(String[] args) {
int n = 10; // 指定生成前n项
int t1 = 0, t2 = 1;
System.out.print("Fibonacci Series up to " + n + ": ");
while (n > 0) {
System.out.print(t1 + ", ");
int sum = t1 + t2;
t1 = t2;
t2 = sum;
n--;
}
}
}
```
**For循环实现:**
```java
public class Fibonacci {
public static void main(String[] args) {
int n = 10;
int[] fibSeries = new int[n];
fibSeries[0] = 0;
fibSeries[1] = 1;
for (int i = 2; i < n; i++) {
fibSeries[i] = fibSeries[i - 1] + fibSeries[i - 2];
}
System.out.println("Fibonacci Series up to " + n + ": ");
for (int num : fibSeries) {
System.out.print(num + ", ");
}
}
}
```
这两个程序都会打印出指定数量(这里是10项)的斐波那契数列。
阅读全文