原题链接:PTA | 程序设计类实验辅助教学平台
Tips:以下Python代码仅个人理解,非最优算法,仅供参考!多学习其他大佬的AC代码!
测试点2:如果 K
为 1,则输出 The average of 1 number is Y
一开始做的时候测试点2答案错误,请注意number不是numbers,Y是float形式2位小数
def main():
n = int(input())
_nums = list(map(str,input().split()))
# nums = []
cnt = sum = 0
for i in _nums:
try:
num = float(i)
except:
print(f'ERROR: {i} is not a legal number')
continue
if num > 1000 or num < -1000:
print(f'ERROR: {i} is not a legal number')
continue
tmp = str(num)
frac = tmp[tmp.find('.')+1:]
if len(frac) > 2:
print(f'ERROR: {i} is not a legal number')
continue
cnt += 1
sum += num
if cnt == 0:
print('The average of 0 numbers is Undefined')
elif cnt == 1:
print(f'The average of {cnt} number is {sum/cnt:.2f}')
else:
print(f'The average of {cnt} numbers is {sum/cnt:.2f}')
main()