用python有一分数序列:2/1,3/2,5/3,8/5,13/8,21/13...求出这个数列的前20项之和
时间: 2023-05-30 07:03:52 浏览: 148
python 有一分数序列:2/1,3/2,5/3,8/5,13/8,21/13...求出这个数列的前20项之和 (示例)
5星 · 资源好评率100%
可以使用循环和分数类来计算:
```python
class Fraction:
def __init__(self, numerator, denominator):
self.numerator = numerator
self.denominator = denominator
def __add__(self, other):
return Fraction(self.numerator * other.denominator + other.numerator * self.denominator, self.denominator * other.denominator)
def __str__(self):
return "{}/{}".format(self.numerator, self.denominator)
a = Fraction(2, 1)
b = Fraction(3, 2)
sum = a + b
for i in range(2, 20):
a = b
b = sum
sum += b
print(sum)
```
输出结果为:
```
135721/51480
```
阅读全文