Description
本题的基本要求非常简单:给定 N 个实数,计算它们的平均值。但复杂的是有些输入数据可能是非法的。一个“合法”的输入是 [−1000,1000] 区间内的实数,并且最多精确到小数点后 2 位。当你计算平均值的时候,不能把那些非法的数据算在内。
Input
输入第一行给出正整数 N(≤100)。随后一行给出 N 个实数,数字间以一个空格分隔。
Output
对每个非法输入,在一行中输出 ERROR: X is not a legal number,其中 X 是输入。最后在一行中输出结果:The average of K numbers is Y,其中 K 是合法输入的个数,Y 是它们的平均值,精确到小数点后 2 位。如果平均值无法计算,则用 Undefined 替换 Y。如果 K 为 1,则输出 The average of 1 number is Y。
参考程序
def SplitFloat(num):#输入num是字符串类型的小数
ind=num.index(".")
if len(num[ind+1:])>=3:
return False
else:
return True
N=int(input())
ls=list(input().split())
SUM=0
cnt=0
for i in ls:
try:
temp=float(i)
if temp>1000 or temp<-1000:
print("ERROR: {} is not a legal number".format(i))
else:
if "." in i:#是浮点数
if SplitFloat(i):#位数满足要求
SUM+=temp
cnt+=1
else:
print("ERROR: {} is not a legal number".format(i))
else:#是整数
SUM+=temp
cnt+=1
except:
print("ERROR: {} is not a legal number".format(i))
if cnt>1:
print("The average of {0} numbers is {1:.2f}".format(cnt,SUM/cnt))
elif cnt==1:
print("The average of {0} number is {1:.2f}".format(cnt,SUM/cnt))
else:
print("The average of {0} numbers is Undefined".format(cnt))
说明:
本题简单使用了异常处理机制,对于一个输入,在将字符串转换为浮点数的过程中使用异常监测;若转换成功则就是正常地浮点数,作进一步处理(还要监测小数位数),若无法准换则直接交给异常来处理,无需自己设计判断是否为浮点数。
另外还要考虑,若只有1个合法数值,那么根据题目要求,number不要加s(单复数),这一点需要考虑到。