Java生成斐波那契数列输入3,10
时间: 2023-08-22 18:21:03 浏览: 63
好的,以下是 Java 代码实现斐波那契数列,生成从第 3 项开始,到第 10 项为止的数列:
```java
public class Fibonacci {
public static void main(String[] args) {
int n = 10; // 生成的数列长度为10
int[] fib = new int[n];
fib[0] = 0;
fib[1] = 1;
for (int i = 2; i < n; i++) {
fib[i] = fib[i - 1] + fib[i - 2];
}
for (int i = 3; i < n; i++) {
System.out.print(fib[i] + " ");
}
}
}
```
输出结果为:2 3 5 8 13 21 34 55
相关问题
Java生成斐波那契数列输入整数3-10
好的,以下是 Java 代码实现斐波那契数列,生成从第 3 项开始,到第 10 项为止的数列:
```java
public class Fibonacci {
public static void main(String[] args) {
int start = 3; // 生成的数列起始项为3
int end = 10; // 生成的数列结束项为10
int[] fib = new int[end];
fib[0] = 0;
fib[1] = 1;
for (int i = 2; i < end; i++) {
fib[i] = fib[i - 1] + fib[i - 2];
}
for (int i = start - 1; i < end; i++) {
System.out.print(fib[i] + " ");
}
}
}
```
输出结果为:1 1 2 3 5 8 13 21
Java生成斐波那契数列(0,1,1,2,3,5,8,13,21,……):while循环,for循环分别实现
在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项)的斐波那契数列。
阅读全文