【发布时间】:2019-05-15 08:20:11
【问题描述】:
我正在尝试编写一个程序来使用 Python 计算斐波那契数:
n = int(input())
def fib(n):
a = []
if (n <=1):
return n
else:
for i in range(2, n):
a.append(a[-1] + a[-2])
return a[i]
print (fib(n))
但是,我无法打印出预期的结果。例如,我输入数字 8 后,弹出如下信息:
Traceback (most recent call last):
File "fibonacci.py", line 11, in <module>
print (fib(n))
File "fibonacci.py", line 9, in fib
a.append(a[-1] + a[-2])
IndexError: list index out of range
在这个过程中出了什么问题?提前致谢。
【问题讨论】:
-
IndexError: list index out of rangeyour'e 从一个空数组开始并尝试访问其上的索引。