本題的基本要求非常簡單:給定 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
作者: CHEN, Yue
單位: 浙江大學
時間限制: 400 ms
內存限制: 64 MB
代碼長度限制: 16 KB
#include<iostream>
#include<string>
using namespace std;
int main(){
while(1){
int n,size,di,sum=0,fi;
scanf("%d",&n);
string s;
double num,ave=0;
int flag,x=0;
for(int i=0;i<n;++i){
cin>>s;
size=s.length();
fi=s.find('.');
if(size-fi>3&&fi!=-1){//一定要有fi!+-1不然-99之類的會掛。。
printf("ERROR: %s is not a legal number\n",s.c_str());
continue;
}
di=0;
flag=1;
if((s[0]>='0'&&s[0]<='9')||s[0]=='-'){
for(int i=1;i<size;++i){
if(s[i]=='.')
++di;
if(((s[i]<'0'||s[i]>'9')&&s[i]!='.')||(di>1)){
printf("ERROR: %s is not a legal number\n",s.c_str());
flag=0;
break;
}
}
if(flag==1){
num=atof(s.c_str());
if(num>1000||num<-1000)
printf("ERROR: %s is not a legal number\n",s.c_str());
else{
ave+=num;
++x;
//cout<<num<<endl;
//cout<<"ave="<<ave<<" x="<<x<<endl;
}
}
}else{
printf("ERROR: %s is not a legal number\n",s.c_str());
}
}
if(x==0){
printf("The average of 0 numbers is Undefined\n");
}else if(x==1){
printf("The average of 1 number is %.2lf\n",ave);
}else{
printf("The average of %d numbers is %.2lf\n",x,ave/x);
}
}
}
#include<iostream>
#include<string>
#include<sstream>
#include<algorithm>
using namespace std;
int main(){
int nn=0,n,dian,size;
double sum=0,num=0;
string s;
scanf("%d",&n);
while(n--){
cin>>s;
size=s.length();
dian=s.find('.');
if(size-dian>3&&dian!=-1){//這一句以及它的位置是核心
cout<<"ERROR: "<<s<<" is not a legal number"<<endl;
continue;
}
num=0;
dian=0;//兩個dian含義不同
bool flag=true;
if((s[0]=='-'&&size>1)||(s[0]>='0'&&s[0]<='9')){
for(int i=1;i<size;++i){
if(s[i]=='.'){
++dian;
}else if(s[i]<'0'||s[i]>'9'){
flag=false;
break;
}
}
if(flag==false||dian>1){
cout<<"ERROR: "<<s<<" is not a legal number"<<endl;
continue;
}
num=atof(s.c_str());
///////
//cout<<num<<endl;
if((num>1000||num<-1000)){
cout<<"ERROR: "<<s<<" is not a legal number"<<endl;
continue;
}
++nn;
sum+=num;
}else{
cout<<"ERROR: "<<s<<" is not a legal number"<<endl;
}
}
if(nn==0)
cout<<"The average of 0 numbers is Undefined"<<endl;
else if(nn==1)
printf("The average of 1 number is %.2lf\n",sum);
else
printf("The average of %d numbers is %.2lf\n",nn,sum/(nn*1.0));
}