斐波那切数列的前两项均为1,从第3项开始,每一项的值为前两项的和,有input的函数输入一个n(大于2)的值,输出斐波那切数列的前n项组成的列表,用python,完整代码+注释
时间: 2024-10-19 16:15:01 浏览: 27
java编程裴波那契数列N项求和pbnq-java.zip
斐波那契数列是一个经典的数学序列,它的特点是每个数字都是前两个数字之和。以下是使用Python编写的一个函数,该函数接受一个正整数n作为输入,并生成斐波那契数列的前n项:
```python
def fibonacci(n):
"""
This function generates the Fibonacci sequence up to n terms.
Parameters:
n (int): The number of terms in the sequence.
Returns:
list: A list containing the first n Fibonacci numbers.
"""
# 初始化斐波那契序列的前两项
fib_sequence = [1, 1]
# 如果n小于等于2,直接返回序列
if n <= 2:
return fib_sequence[:n]
# 通过循环计算并添加剩余的项
for i in range(2, n):
next_number = fib_sequence[i - 1] + fib_sequence[i - 2]
fib_sequence.append(next_number)
return fib_sequence
# 获取用户输入
n_terms = int(input("Enter a positive integer for the number of terms you want in the Fibonacci sequence: "))
# 输出斐波那契数列
result = fibonacci(n_terms)
print(f"The first {n_terms} terms of the Fibonacci sequence are: {result}")
#
阅读全文