用java输出斐波那契的前20项
时间: 2023-05-12 18:05:13 浏览: 102
以下是用 Java 输出斐波那契数列前 20 项的代码:
```java
public class Fibonacci {
public static void main(String[] args) {
int n = 20, t1 = 0, t2 = 1;
System.out.print("前 " + n + " 项斐波那契数列:");
for (int i = 1; i <= n; ++i) {
System.out.print(t1 + " + ");
int sum = t1 + t2;
t1 = t2;
t2 = sum;
}
}
}
```
输出结果为:
```
前 20 项斐波那契数列:0 + 1 + 1 + 2 + 3 + 5 + 8 + 13 + 21 + 34 + 55 + 89 + 144 + 233 + 377 + 610 + 987 + 1597 + 2584 + 4181 +
```
相关问题
通过Java用递归输出斐波那契前15项
好的,以下是通过Java用递归输出斐波那契前15项的代码:
```
public class Fibonacci {
public static void main(String[] args) {
for (int i = 1; i <= 15; i++) {
System.out.print(fibonacci(i) + " ");
}
}
public static int fibonacci(int n) {
if (n == 1 || n == 2) {
return 1;
} else {
return fibonacci(n - 1) + fibonacci(n - 2);
}
}
}
```
输出结果为:1 1 2 3 5 8 13 21 34 55 89 144 233 377 610
用java输出斐波那契数列的前10项
可以使用以下代码输出斐波那契数列的前10项:
```
public class Fibonacci {
public static void main(String[] args) {
int n = 10, t1 = , t2 = 1;
System.out.print("前 " + n + " 项斐波那契数列: ");
for (int i = 1; i <= n; ++i) {
System.out.print(t1 + " + ");
int sum = t1 + t2;
t1 = t2;
t2 = sum;
}
}
}
```
输出结果为: + 1 + 1 + 2 + 3 + 5 + 8 + 13 + 21 + 34 +
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)