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

Python计算i从0到5的H值累加和 代码问题求助

代码问题修正

你的代码有两处核心逻辑错误,导致无法得到正确的总累加结果:

  • 累加变量summation初始化位置错误:summation=0被写在while循环内部,每次循环执行时都会把之前累加的结果重置为0,最终变量里只存了当前i对应的单轮H值和,无法累计所有轮次的计算结果。
  • 输出语句位置错误:print(summation)放在循环内部会逐轮打印临时值,无法直接输出0到5全范围的总累加和。

修正后的代码:

i = 0
he = float(input("he:"))
summation = 0  # 累加器移到循环外,仅初始化一次
while i < 6:
    H1 = 100 - ((2 * i * 1500) - he)
    H2 = 120 + ((2 * i * 1200) - he)
    H3 = 200 - ((2 * i * 1100) + he)
    H4 = 80 + ((2 * i * 1100) + he)
    summation += H1 + H2 + H3 + H4
    i += 1
print(summation)  # 循环全部执行完成后,再打印最终总累加值

如果你需要同时查看每个i对应的单轮计算结果,可以在循环内增加单轮值的打印逻辑,参考写法:

i = 0
he = float(input("he:"))
summation = 0
while i < 6:
    H1 = 100 - ((2 * i * 1500) - he)
    H2 = 120 + ((2 * i * 1200) - he)
    H3 = 200 - ((2 * i * 1100) + he)
    H4 = 80 + ((2 * i * 1100) + he)
    round_sum = H1 + H2 + H3 + H4
    print(f"i={i} 对应单轮H值和:{round_sum}")
    summation += round_sum
    i += 1
print(f"所有轮次累加总和:{summation}")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 18:15:51