用Java语言编写一个斐波那契数列前二十位并输出
时间: 2023-05-11 10:03:22 浏览: 187
Sure, here is the Java code to generate the first 20 numbers in the Fibonacci sequence:
```
public class Fibonacci {
public static void main(String[] args) {
int n = 20, t1 = 0, t2 = 1;
System.out.print("First " + n + " terms: ");
for (int i = 1; i <= n; ++i) {
System.out.print(t1 + " + ");
int sum = t1 + t2;
t1 = t2;
t2 = sum;
}
}
}
```
This code will output the first 20 numbers in the Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181.
相关问题
java代码编写一个斐波那契数列
好的,下面是Java代码实现斐波那契数列:
```
public class FibonacciSeries {
public static void main(String[] args) {
int n = 10;
int t1 = 0, t2 = 1;
System.out.print("First " + n + " terms: ");
for (int i = 1; i <= n; ++i) {
System.out.print(t1 + " + ");
int sum = t1 + t2;
t1 = t2;
t2 = sum;
}
}
}
```
运行结果为:
```
First 10 terms: 0 + 1 + 1 + 2 + 3 + 5 + 8 + 13 + 21 + 34 +
```
请问还有什么其他问题吗?
用java语言编写一个数学数列
斐波那契数列
斐波那契数列(Fibonacci sequence),又称黄金分割数列,指的是这样一个数列:0、1、1、2、3、5、8、13、21、34、……
在数学上,斐波那契数列以如下被以递归的方法定义:
F(0)=0,F(1)=1,
F(n)=F(n-1)+F(n-2)(n≥2,n∈N*)
Java 实现:
public class FibonacciSequence {
public static void main(String[] args) {
int n = 10;
System.out.println("斐波那契数列的前 " + n + " 项为:");
for (int i = 0; i < n; i++) {
System.out.print(fibonacci(i) + " ");
}
}
public static int fibonacci(int n) {
if (n == 0) {
return 0;
} else if (n == 1) {
return 1;
} else {
return fibonacci(n - 1) + fibonacci(n - 2);
}
}
}
输出结果:
斐波那契数列的前 10 项为:
0 1 1 2 3 5 8 13 21 34
阅读全文