用python求斐波那契数列和斐波那契数列和
时间: 2023-11-23 16:57:40 浏览: 88
使用python求斐波那契数列中第n个数的值示例代码
5星 · 资源好评率100%
以下是两种Python求斐波那契数列和的例子:
1. 求斐波那契数列前n项和
```python
def fibonacci_sum(n):
if n <= 0:
return 0
elif n == 1:
return 1
else:
a, b = 0, 1
sum = 1
for i in range(2, n+1):
c = a + b
sum += c
a, b = b, c
return sum
# 示例
print(fibonacci_sum(10)) # 输出:143
```
2. 求斐波那契数列第n个数的值
```python
def fibonacci(n):
if n <= 0:
return 0
elif n == 1:
return 1
else:
a, b = 0, 1
for i in range(2, n+1):
c = a + b
a, b = b, c
return b
# 示例
print(fibonacci(10)) # 输出:55
```
阅读全文