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

使用while循环计算数组平均高度时触发索引越界错误求助

解决while循环计算数组平均高度的索引越界问题

错误原因分析

  • 循环条件h[i] > 0逻辑缺陷:数组最后一个元素h[4] = 0.5满足大于0的条件,会触发i += 1使索引变为5,超出数组的合法索引范围(数组长度为5,索引仅0-4),直接抛出越界错误。
  • 累加顺序错误:先执行i = i + 1再取h[i],导致数组第一个元素h[0]从未被加入总和,结果本身也不符合预期。

修正方案一:基于索引范围的标准while循环

这种方法确保索引始终在合法范围内,同时正确累加所有元素:

import numpy as np
N=5
h = np.zeros(N) # heights of family members (in meters)
h[0] = 1.60; h[1] = 1.85; h[2] = 1.75; h[3] = 1.80; h[4] = 0.50

i = 0
sum = 0

while i < N:
    sum = sum + h[i]
    i = i + 1

average = sum/N
print('Average height: {:g} meters'.format(average))

修正方案二:兼容过滤0值需求的循环

如果需要跳过高度为0的元素(假设存在此类场景),可以先判断索引合法性,再处理元素:

import numpy as np
N=5
h = np.zeros(N) # heights of family members (in meters)
h[0] = 1.60; h[1] = 1.85; h[2] = 1.75; h[3] = 1.80; h[4] = 0.50

i = 0
sum = 0
valid_count = 0

while i < N:
    if h[i] > 0:
        sum += h[i]
        valid_count += 1
    i += 1

# 避免除以0的情况
average = sum/valid_count if valid_count > 0 else 0
print('Average height: {:g} meters'.format(average))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 16:40:04