本题的基本要求非常简单:给定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 numberThe average of 0 numbers is Undefined
分析:
先判断输入的字符串是否为合格,1.若字符串中含有除了数字,‘-’,‘.’之外的字符,则不合格;2.如果含有两个及以上的‘.’,则不合格;3.如果小数点后有超过两位的数
字,则不合格;4.如果数值范围不在[-1000,1000],则不合格.将合格的字符串转为数字型然后加入到ave中,最后按要求输出,有三种不同的情况,一一讨论输出.
源代码:
#include<iostream> #include<string> #include<iomanip> #include<cctype> #include<vector> using namespace std; double tonum(string s) { double t1=0;double t2=0;int f=1; int i;int index=0; if(s[0]=='-') { f=-1; index=1; } for(i=index;i<s.length()&&s[i]!='.';i++); for(int j=index;j<i;j++) t1=t1*10+s[j]-'0'; for(int j=s.length()-1;j>=i+1;j--) t2=(t2+s[j]-'0')*0.1; return (t1+t2)*f; } int main() { int N;cin>>N; vector<string> s(N); vector<bool> b(N); int t;//记录小数点的位数 int index;//记录小数点的位置 int num=0; double ave=0; for(int i=0;i<N;i++) { b[i]=true;t=0;index=0; cin>>s[i]; for(int j=0;j<s[i].length();j++) { if(!isdigit(s[i].at(j))&&s[i].at(j)!='.'&&s[i].at(j)!='-') { b[i]=false; break; } if(s[i].at(j)=='.') { t++; index=j; } } if(t>1)b[i]=false; else if(t==1&&s[i].length()-index>3) b[i]=false; if(tonum(s[i])>1000||tonum(s[i])<-1000) b[i]=false; if(b[i]) { num++; ave+=tonum(s[i]); } } for(int i=0;i<N;i++) { if(!b[i]) cout<<"ERROR: "<<s[i]<<" is not a legal number"<<endl; } cout<<fixed<<setprecision(2); if(num==0) cout<<"The average of 0 numbers is Undefined"<<endl; else if(num==1) cout<<"The average of 1 number is "<<ave<<endl; else cout<<"The average of "<<num<<" numbers is "<<ave/num<<endl; return 0; }