查看原题目请点我
解题思路:字符串处理,我这里完全是手动判断,注意2.也是合法的浮点数,后面有个点,我分了两个小数和一个小数,最后还要加没有小数部分只有小数点的情况。
#include<cstdio>
#include<cstring>
double ans;
int check(char s[]){
int len=strlen(s);
double tmp=0;
int tag=1;
for(int i=0;i<len;i++){
if(s[i]=='-'){
i++;
tag=2;
}
if((s[i]>='0'&&s[i]<='9')||s[i]=='.'){
if(s[i]=='.'){
if(s[i+1]>='0'&&s[i+1]<='9'&&s[i+2]>='0'&&s[i+2]<='9'&&i==len-3){
ans = tmp+(s[i+1]-'0')*0.1 +(s[i+2]-'0')*0.01;
if(tag==2) ans=-ans;
return 1;
}else if(s[i+1]>='0'&&s[i+1]<='9'&&i==len-2){
ans = tmp+(s[i+1]-'0')*0.1;
if(tag==2) ans=-ans;
return 1;
}else if(i==len-1){
ans=tmp;
if(tag==2) ans=-ans;
return 1;
}else return 0;
}else{
tmp = tmp*10 + s[i]-'0';
}
}else return 0;
}
ans = tmp;
if(tag==2) ans = -ans;
return 1;
}
int main(){
int N;
scanf("%d",&N);
char str[100];
int count = 0;
double sum=0;
for(int i=0;i<N;i++){
ans=0;
scanf("%s",str);
if(check(str)==0||ans<-1000||ans>1000)
printf("ERROR: %s is not a legal number\n",str);
else{
sum += ans;
count++;
}
}
if(count==0)
printf("The average of 0 numbers is Undefined\n");
else if(count==1)
printf("The average of 1 number is %.2f\n",sum);
else
printf("The average of %d numbers is %.2f\n",count,sum/count);
return 0;
}