用while语句实现斐波那契数列
时间: 2023-12-04 16:39:38 浏览: 43
以下是两种使用while语句实现斐波那契数列的方法:
方法1:
```java
int num1 = 1;
int num2 = 1;
int count = 1;
System.out.print("1 1 ");
while(count <= 28){
int temp = num1;
num1 = num2;
num2 += temp;
System.out.print(num2 + " ");
count +=1;
}
```
方法2:
```java
int i = 1;
int first = 1;
int second = 1;
System.out.print("1 1 ");
while(i <= 14){
first += second;
second += first;
System.out.print(first+" "+second+" ");
i += 1;
}
```
相关问题
用递归的方法并用while语句编写斐波那契数列
递归方法实现斐波那契数列:
```python
def fibonacci_recursive(n):
if n <= 1:
return n
else:
return fibonacci_recursive(n-1) + fibonacci_recursive(n-2)
```
使用 while 语句实现斐波那契数列:
```python
def fibonacci_while(n):
a, b = 0, 1
while n > 0:
a, b = b, a + b
n -= 1
return a
```
这两种方法都可以计算斐波那契数列,但递归方法的效率较低,当计算大量的斐波那契数时会出现栈溢出的问题。使用 while 语句可以避免这个问题。
Python如何用while语句输出斐波那契数列的前20项
以下是Python用while语句输出斐波那契数列的前20项的代码:
```
a, b = 0, 1
count = 0
while count < 20:
print(b)
a, b = b, a + b
count += 1
```
该段代码输出的结果如下:
```
1
1
2
3
5
8
13
21
34
55
89
144
233
377
610
987
1597
2584
4181
6765
```