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

Python手动遍历用户输入温度列表求最大值结果错误如何解决

错误原因

  • 直接触发异常的核心问题:你在手动遍历温度列表时,使用for temp in range(0, len(tempList))写法,此时循环变量temp拿到的是列表的索引值,不是列表中存储的温度数值。比如你输入3个温度,循环中temp的取值依次是0、1、2,对比后得到的最大值自然是2,和你输入的36.5没有任何关系。
  • 隐藏逻辑漏洞:你把最大值的初始值设为0.00,如果后续输入的所有温度都是负数,最终计算出来的最大值会错误地保持为0。
  • 额外注意:你在代码里先调用了内置函数max(tempList),后续又用max作为变量名,这会覆盖Python内置的max函数,后续如果再要调用max()函数会报错,建议自定义变量名不要和内置函数重名。

修正后代码

tempList = []

for i in range(0, int(input("How many temps? "))):
    temp = float(input("Input a temp: "))
    tempList.append(temp)

# 手动计算最大值逻辑
max_temp = tempList[0] # 初始值设为列表第一个元素,避免全负数场景错误
for temp in tempList: # 直接遍历列表取温度数值,不要遍历range生成的索引
    if temp > max_temp:
        max_temp = temp
        
print("Temps are: ", tempList, "and the max temp is:", max_temp)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 10:36:03