用Java语言编写一个斐波那契数列前二十位并输出
时间: 2023-05-11 12:03:22 浏览: 85
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语言编写一个数学数列
斐波那契数列
斐波那契数列(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
用Java编写一个求斐波那契数列的程序
您好!以下是一个用Java编写的求斐波那契数列的程序示例:
```java
public class Fibonacci {
public static void main(String[] args) {
int n = ; // 要求的斐波那契列长度
System.out.println("斐波那契数列前 " + n + " 项为:");
for (int i = 0; i < n; i++) {
System.out.print(fonacci(i) + " ");
}
}
public static int fibonacci(int num) {
if (num == 0 || num == 1) {
return num;
} else {
return fibonacci(num - 1) + fibonacci(num - 2);
}
}
}
```
这段代码通过递归的方式计算斐波那契数列的前n项,并将结果打印出来。在上述示例中,我们设置n为10,您可以根据需要修改这个值。运行程序后,您将会看到输出结果为斐波那契数列的前10项。
希望对您有帮助!如果您有任何其他问题,请随时提问。