这道题考的还是字符串的处理问题
测试点二三出错的同学,请好好看一下下面两句话。。。
The average of 1 number is YThe average of K numbers is Y
看你有没有把1 number单独列出来,还是输出的也是1 numbers
本人代码其实过不了有些样例,比如输入".6"其实是非法的,但是测试数据中也没有这样的,就算水过了这道题吧QAQ
#include<bits/stdc++.h>
using namespace std;
const int maxn=105;
int n;
double ans;
string str[maxn];
bool vis[maxn];
int find(string str) {int h,length=str.length();for(int i=0; i<length; i++) {if(str[i]=='.') {h=i;return h;}}return -1;
}
double convert(string str) {int length=str.length();double sum=0,sum2=0;int h=find(str);h=length-h-1;for(int i=0; i<length; i++) {if(str[i]=='-'&&i==0) continue;if(str[i]!='.') {sum*=10;sum+=(str[i]-'0');} else {for(int j=i+1; j<length; j++) {sum2*=10;sum2+=(str[j]-'0');}while(h--) sum2/=10;sum+=sum2;break;}}if(str[0]=='-') return -sum;else return sum;
}
bool judge(string str) {int h=find(str);int length=str.length();if(h!=-1&&length-h-1>2) return true;if(convert(str)<-1000||convert(str)>1000) return true;for(int i=0; i<length; i++) {if(str[i]=='-'){if(i==0) continue;else return true;} if(str[i]=='.') {if(i!=h) return true;} else if(str[i]<'0'||str[i]>'9') return true;}return false;
}
int main() {int count=0;cin>>n;for(int i=0; i<n; i++) {cin>>str[i];if(judge(str[i])) vis[i]=1;else {ans+=convert(str[i]);count++;}}for(int i=0; i<n; i++) {if(vis[i]) {cout<<"ERROR: "<<str[i]<<" is not a legal number"<<endl;}}if(count==0) printf("The average of 0 numbers is Undefined\n");else if(count==1) printf("The average of %d numbers is %.2lf\n",count,ans/count);else printf("The average of %d numbers is %.2lf\n",count,ans/count);return 0;
}