这题主要在于分辨是不是符合要求的数,这个用异常处理可以简单达到
题目简单就直接上代码了:
n = int(input())
x = list(input().split())
num = 0
m = 0
for i in x:
try:
j = float(i)
if -1000 <= j <= 1000 and round(j,2) == j:#在范围内且最多只有两位小数
num +=j
m +=1
else:
print('ERROR: '+str(i)+' is not a legal number')
except:
print('ERROR: ' + str(i) + ' is not a legal number')
if m == 0:
print('The average of 0 numbers is Undefined')
else:
num = num / m
if m == 1:
print('The average of ' + str(m) + ' number is ', end='')
print('%.2f' % (num))
else:
print('The average of ' + str(m) + ' numbers is ', end='')
print('%.2f' % (num))
提交截图:

本文介绍了一种使用异常处理来筛选合法数值并计算其平均数的方法。通过输入一系列字符串形式的数字,程序能够准确判断哪些是有效数值,并计算这些数值的平均数。对于不符合条件的数据,程序会输出错误提示。

被折叠的 条评论
为什么被折叠?



