You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在列表中生成斐波那契序列代码运行异常,求定位错误原因

代码问题分析
  • 硬编码初始序列first_sequence = ([2, 3]),会覆盖用户输入的first_value和second_value,不管用户输入什么初始值,序列前两位永远是2、3,不符合自定义输入的需求。
  • 序列初始化长度错误:sequence = first_sequence + ([0] * number_of_sequence),如果要生成number_of_sequence长度的序列,初始已经有2个元素,只需要补充number_of_sequence - 2个占位0即可,当前写法会导致序列长度超出预期。
  • 循环范围错误:range (1, number_of_sequence-1)的遍历范围会少生成目标数量的斐波那契元素,无法填满目标长度的序列。
  • 赋值逻辑错误:second_value = sequence直接把整个列表赋值给了变量second_value,下一轮循环执行first_value + second_value时会触发整数和列表相加的类型报错,这里应该赋值为新计算出来的序列元素值。
  • 打印逻辑错误:print语句放在循环内部,每次循环都会打印一次当前的序列,会输出多段不完整的序列,应该等循环结束后统一打印最终结果。
修正后代码
print('============FIBONACCI SEQUENCE PROGRAM===============')

number_of_sequence = int(input('Type the number of sequence = '))
# 若不需要自定义初始值,直接把下面两行改为 first_value = 2、second_value = 3即可
first_value = int(input('Insert the first value = '))
second_value = int(input('Insert the second value = '))

sequence = [first_value, second_value]

for i in range(2, number_of_sequence):
    next_val = first_value + second_value
    sequence.append(next_val)
    first_value = second_value
    second_value = next_val

# 按预期格式输出无逗号、空格分隔的带括号结果
print(f"[{' '.join(map(str, sequence))}]")

当输入序列长度为9、初始值为2和3时,输出结果为[2 3 5 8 13 21 34 55 89],符合需求。

内容的提问来源于stack exchange,提问作者ratu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 06:57:03