Python exercise 4.8 find the sum of the first N items of the fraction sequence

This question requires a program to calculate the sum of the first N items of the sequence 2/1 + 3/2 + 5/3 + 8/5 + ... Note that the sequence starts from item 2, the numerator of each item is the sum of the previous item's numerator and the denominator, and the denominator is the previous item's numerator.

Input format:

The input gives a positive integer N on one line.

Output format:

The value of the partial sum is output in one line, accurate to two decimal places. The problem is to ensure that the calculation result does not exceed the double precision range.

code show as below:

#!/usr/bin/python
# -*- coding: utf-8 -*-

def f(n):
    a = 2
    b = 1
    c = 1
    while n>=2:
        c = a+b
        b = a
        a = c
        n -= 1
    return a/b

n = int(input())
sum = 0
for i in range(1,n+1):
    sum +=f(i)
print("{:.2f}".format(sum))

Define a method as before, find the number for each digit. Then the loop summation is performed.


There is always a book and fitness on the road

Guess you like

Origin www.cnblogs.com/Renqy/p/12733070.html