我试图找到包含不同高度的数组的平均高度。 我必须使用 while 循环找到它。以前我用 for 循环做到了这一点并且它有效,但是当我尝试这种方式时,我不断收到越界错误。
我多次尝试更改 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 h[i] > 0:
i = i + 1
sum = sum + h[i]
average = sum/N
print('Average height: {:g} meters'.format(average))
您可以使用基于
i < N
的条件来确保不会超出范围并在递增 i
之前累加总和:
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
total_sum = 0
while i < N:
total_sum += h[i]
i += 1
average = total_sum / N
print(f'Average height: {average:g} meters')
np.mean
:
average = np.mean(h)
print(f'Average height: {average:g} meters')
两种方法的输出:
Average height: 1.5 meters