『题目』
本题的基本要求非常简单:给定N个实数,计算它们的平均值。但复杂的是有些输入数据可能是非法的。一个“合法”的输入是[-1000,1000]区间内的实数,并且最多精确到小数点后2位。当你计算平均值的时候,不能把那些非法的数据算在内。
输入格式:
输入第一行给出正整数N(<=100)。随后一行给出N个实数,数字间以一个空格分隔。
输出格式:
对每个非法输入,在一行中输出“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”。
输入样例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
『思路』
思路依然很简单,
三点要求:
除了符号外,只能包含数字和小数点;
小数点只能有一位;
小数点后最多有两位。
这道题确实是非常的坑,题目很不严谨,像这种对输出格式要求很高的题目,应该描述得更加清晰才是。
题目对 001、000.01、12. 这种数据居然都是接受的
第三个测试点是当K等于1的情况
第四个测试点是[-1000,1000]边界情况。
『AC代码』
#include <iostream>
#include <cstring>
#include <cmath>
#include <cstdlib>
using namespace std;
//字符转换成数字
double tra(char *s) {
double a=atof(s);
return a;
}
int main() {
int N;
cin>>N;
double ans,sum = 0,k = 0;
char s[N+1][1000];
for(int i =0; i < N; i++) {
scanf("%s",s[i]);
//puts(s[i]);
//cout<<endl;
int len = strlen(s[i]),flag = 0,p = 0,p_ = 0;
//cout<<"len ="<<len<<endl;
if(s[i][0] == '-') {//判断第一位是否是负号
for(int j = 1; j < len; j++) {
if(s[i][j] == '.')//判断有多少小数点
p++;
if(p == 1) p_++;//p_判断小数点后有多少位数
}
for(int j = 1; j < len; j++) {
if((!(s[i][j] >= '0' && s[i][j] <= '9') && s[i][j] != '.' ) || (p > 1) || p_ > 3 ) {
cout<<"ERROR: ";
printf("%s",s[i]);
cout<<" is not a legal number"<<endl ;
flag = 1;
break;
}
}
} else {
for(int j = 0; j < len; j++) {
if(s[i][j] == '.')
p++;
if(p == 1) p_++;
}
for(int j = 1; j < len; j++) {
if((!(s[i][j] >= '0' && s[i][j] <= '9') && s[i][j] != '.') || (p > 1) || p_ > 3) {//如果 不是数字,或小数点数大于1,或小数点后位数多于2 则非法
cout<<"ERROR: ";
printf("%s",s[i]);
cout<<" is not a legal number"<<endl ;
flag = 1;
break;
}
}
}
if(!flag) {
ans = tra(s[i]);
//cout<<"ans="<<ans<<endl;
if(abs(ans) <= 1000) {
sum+=ans;
//cout<<"sum="<<sum<<endl;
k++;
}
else{
cout<<"ERROR: ";
printf("%s",s[i]);
cout<<" is not a legal number"<<endl ;
}
}
}
if(k == 0){
cout<<"The average of "<<k<<" numbers is Undefined";
}
else if(k == 1){
cout<<"The average of "<<k<<" number is ";
printf("%.2lf",sum/k);
}
else{
cout<<"The average of "<<k<<" numbers is ";
printf("%.2lf",sum/k);
}
return 0;
}
『写在最后的一些话』
牛羊,说我每天写PAT很水,作为一个蒟蒻,迷宫写的真的很费精神啊,这里错那里错的,还不能写一些简单的(相对)PAT水一下么,好吧好吧,每天除了基础知识再加一篇PAT。
Stay hungry ,stay foolish。