用python来解PAT乙级1054求平均值-20-满分
这题主要在于分辨是不是符合要求的数,这个用异常处理可以简单达到
题目简单就直接上代码了:
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))
提交截图: