PAT乙级 1054 求平均值
程序员文章站
2022-07-16 07:50:16
...
题目:
输入样例1:
7
5 -3.2 aaa 9999 2.3.4 7.123 2.35
输出样例1:
ERROR: aaa is not a legal number
ERROR: 9999 is not a legal number
ERROR: 2.3.4 is not a legal number
ERROR: 7.123 is not a legal number
The average of 3 numbers is 1.38
输入样例2:
2
aaa -9999
输出样例2:
ERROR: aaa is not a legal number
ERROR: -9999 is not a legal number
The average of 0 numbers is Undefined
Python
分析:
首先以字符串形式接受每个数据,可以尝试直接类型转换为float,出现异常说明数据不是合法的数字,如果可以转换,说明是数字,再看是不是在[-1000,1000]范围内,最后再看小数点位数不多于2位
注意:
当只有0个合法输入时输出:The average of 0 numbers is Undefined
只有1个合法输入时输出的是number,不是numbers
n = int(input())
s = input().split()
total = 0.0
cnt = 0
for i in s:
flag = False
try:
if float(i) < -1000 or float(i) > 1000:
flag = True
elif '.' in i and len(i.split('.')[1]) > 2:
flag = True
else:
cnt += 1
total += float(i)
except ValueError:
flag = True
finally:
if flag:
print("ERROR: " + i + " is not a legal number")
if cnt == 0:
print("The average of 0 numbers is Undefined")
elif cnt == 1:
print("The average of 1 number is " + "%.2f" % total)
else:
print("The average of " + str(cnt) + " numbers is " + "%.2f" % (total / cnt))
C++
分析:
这个是柳婼小姐姐的方法,c++里面用sscanf()竟然可以直接将非数字类型转为数字而不报错!!(虽然这样转成的数字没什么意义,但不报错就好了),那就接收每个要判断的数据a,直接转为double(c++默认的浮点数是double),格式化两位小数赋给b,遍历a,看a的每一位是否与b对应位完全相等,这里会筛出两种非法输入:
1.当len(a)>len(b),此时一定不等,可筛出小数位多于2的情况;
2.当len(a)<=len(b),此时只比较a与b的对应位,可筛出输入不是数字的情况,因为非数字转换为数字两者一定不相等
最后再判断是否 > 1000 或 < -1000,筛出第3种非法输入
至于如何输出和上面用python写的思路一样
附:
sscanf() – 从一个字符串中读进与指定格式相符的数据
sprintf() – 字符串格式化命令,主要功能是把要格式化的数据写入某个字符串中
#include <iostream>
#include <string.h>
using namespace std;
int main() {
int n, cnt = 0;
scanf("%d", &n);
char a[50], b[50];
double temp, sum = 0.0;
for (int i = 0; i < n; i++) {
scanf("%s", a);
sscanf(a,"%lf", &temp);
sprintf(b, "%.2f", temp);
int flag = 0;
for (int j = 0; j < strlen(a); j++)
if (a[j] != b[j]) {
flag = 1;
break;
}
if (flag || temp < -1000 || temp > 1000)
printf("ERROR: %s is not a legal number\n", a);
else {
cnt++;
sum += temp;
}
}
if (cnt == 0)
printf("The average of 0 numbers is Undefined");
else if (cnt == 1)
printf("The average of 1 number is %.2f", sum);
else
printf("The average of %d numbers is %.2f", cnt, sum / cnt);
return 0;
}