python中怎么得出斐波那契数列第n项及前n项和?
2591次观看
标签:
数列
python
老师回答
用for循环求斐波那契数列中第n个数的值:
n = int(input('请输入要一个整数:'))
n_2 = 0
n_1 = 1
current = 1
for x in range(2, n+1):
current = n_2 + n_1
n_2 = n_1
n_1 = current
print('第%d个数是%d'%(n, current))
求斐波那契数列前N项之和:
n = int(input("Input N: "))
a = 0
b = 1
sum = 0
for i in range(n):
sum += a
a, b = b, a + b
print("The sum of", n, "FIB is", sum,"!")
©本文版权归环球青藤所有,任何形式转载请联系我们。
免费直播
精选课程
相关推荐