用python实现斐波那契数列,输入某个数,就输出几位
时间: 2024-10-14 14:17:33 浏览: 30
在Python中,可以使用递归或循环的方式来实现斐波那契数列。如果你想要让用户输入一个数字n,然后输出前n位的斐波那契数,你需要控制输出的长度,因为斐波那契数列本身的每一位都是整数。以下是两个简单的示例:
1. 递归版本(适用于较小的n值,因为递归效率较低,n过大可能导致栈溢出):
```python
def fibonacci(n):
if n <= 0:
return "请输入正整数"
elif n == 1:
return [0]
elif n == 2:
return [0, 1]
else:
fib_sequence = [0, 1]
while len(fib_sequence) < n:
next_num = fib_sequence[-2]
fib_sequence.append(next_num)
return fib_sequence[:n]
# 示例使用
num_of_terms = int(input("请输入一个数字: "))
sequence = fibonacci(num_of_terms)
print("前{}位斐波那契数列为: {}".format(len(sequence), sequence))
```
2. 循环版本(效率更高,适合大数值计算):
```python
def fibonacci(n):
if n <= 0:
return "请输入正整数"
fib_sequence = [0, 1]
for _ in range(2, n):
fib_sequence.append(fib_sequence[-1] + fib_sequence[-2])
return fib_sequence[:n]
# 示例使用
num_of_terms = int(input("请输入一个数字: "))
sequence = fibonacci(num_of_terms)
print("前{}位斐波那契数列为: {}".format(len(sequence), sequence))
```
阅读全文