Python:分数序列求和

#!/usr/bin/env python
# coding:UTF-8


"""
@version: python3.x
@author:曹新健
@contact: [email protected]
@software: PyCharm
@file: 1223.py
@time: 2018/12/23 20:56
"""

'''
有一分数序列:2/1,3/2,5/3,8/5,13/8,21/13...求出这个数列的前20项之和。
'''
"""
#方法一
def g(n):
    if n <= 2:
        return n
    else:
        return g(n-1) + g(n-2)
sum = 0
for i in range(1,21):
    sum += g(i+1)/g(i)

print(sum)
"""

#方法二
numerator = 2
denominator = 1
sum = 0
while True:
    try:
        n = int(input("请输入一个整数:"))
    except ValueError:
        print("输入错误,请输入整数")
    else:
        for i in range(n):
            sum += numerator / denominator
            numerator, denominator = numerator + denominator, numerator

        print(sum)
        break



 

你可能感兴趣的:(Python基础小练习)