题目
思路:
利用异常捕获非法字符,
再判断小数位数是否合法
最后判定是否在规定区间
将合法数字相加求平均
需要注意的是
当合法数字数目为0的输出
当合法数字数目为1时 numbers改为number
区间判定需要为-1000<=num<=1000
代码:
num=int(input())
num_list=list(input().split())
sum_=0
leage_count=0
for str_ in num_list:
try:#判断字符是否可以转为合法数字
temp=float(str_)
point_num = 0
if '.' in str_:
point = str_.index('.')
point_num = len(str_) - point - 1
if point_num>2: #判断小数位数是否合法
print(f'ERROR: {str_} is not a legal number')
continue
if -1000<=temp<=1000:#判断大小是否在合法区间
leage_count=leage_count+1
sum_=sum_+round(temp,2)
else:
print(f'ERROR: {str_} is not a legal number')
except:
print(f'ERROR: {str_} is not a legal number')
if leage_count==0:
print('The average of 0 numbers is Undefined')
elif leage_count==1:
print("The average of {} number is {:.2f}".format(leage_count,sum_/leage_count))
else:
print("The average of {} numbers is {:.2f}".format(leage_count, sum_ /leage_count))