Python程序:计算斐波那契数列和

创新互联python教程:

写一个 Python 程序来找到用于循环的斐波那契数列的和。在这个 Python 例子中,我们使用 for 循环从 0 迭代到 n,并找到该范围内所有斐波那契数列的总和。

Number = int(input("Please Enter the Fibonacci Number Range = "))

First = 0
Second = 1
Sum = 0

for Num in range(0, Number):
    print(First, end = '  ')
    Sum = Sum + First
    Next = First + Second
    First = Second
    Second = Next

print("\nThe Sum of Fibonacci Series Numbers = %d" %Sum)

Python 程序,使用 while 循环查找斐波那契数列的和。

Number = int(input("Please Enter the Fibonacci Numbers Range = "))

First = 0
Second = 1
Sum = 0
i = 0

while(i <  Number):
    print(First, end = '  ')
    Sum = Sum + First
    Next = First + Second
    First = Second
    Second = Next
    i = i + 1

print("\nThe Sum of Fibonacci Series Numbers = %d" %Sum)
Please Enter the Fibonacci Numbers Range = 24
0  1  1  2  3  5  8  13  21  34  55  89  144  233  377  610  987  1597  2584  4181  6765  10946  17711  28657  
The Sum of Fibonacci Series Numbers = 75024

Python 程序用递归或递归函数求所有斐波那契数列的和。

def fibonacci(Number):
    if(Number == 0):
        return 0
    elif Number == 1:
        return 1
    else:
        return fibonacci(Number - 2) + fibonacci(Number - 1)

Number = int(input("Please Enter the Fibonacci Number Range = "))
Sum = 0

for Num in range(Number):
    print(fibonacci(Num), end = '  ')
    Sum = Sum + fibonacci(Num)

print("\nThe Sum of Fibonacci Series Numbers = %d" %Sum)
Please Enter the Fibonacci Number Range = 30
0  1  1  2  3  5  8  13  21  34  55  89  144  233  377  610  987  1597  2584  4181  6765  10946  17711  28657  46368  75025  121393  196418  317811  514229  
The Sum of Fibonacci Series Numbers = 1346268

当前名称:Python程序:计算斐波那契数列和
网页网址:http://www.csdahua.cn/qtweb/news19/337419.html

网站建设、网络推广公司-快上网,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 快上网