# 1108 Finding Average（20 分）【字符串模拟题】

20分的水题，我却写了40多分钟，严重怀疑自己思路错了。A了以后看了别人的解题报告，才发现原来用两个函数就可以很轻松的解决了。。还是要多掌握一些知识呀。。

sscanf() – 从一个字符串中读进与指定格式相符的数据
sprintf() – 字符串格式化命令，主要功能是把格式化的数据写入某个字符串中

#include <string.h>
using namespace std;
int main()
{
int n, cnt = 0;
char a[50], b[50];
double temp, sum = 0.0;
cin >> n;
for(int i = 0; i < n; i++) {
scanf("%s", a);
sscanf(a, "%lf", &temp);
sprintf(b, "%.2lf",temp);
int flag = 0;
for(int j = 0; j < strlen(a); j++) {
if(a[j] != b[j]) {
flag = 1;
}
}
if(flag || temp < -1000 || temp > 1000) {
printf("ERROR: %s is not a legal number\n", a);
continue;
} else {
sum += temp;
cnt++;
}
}
if(cnt == 1)
printf("The average of 1 number is %.2lf", sum);

else if(cnt > 1)
printf("The average of %d numbers is %.2lf", cnt, sum / cnt);

else
printf("The average of 0 numbers is Undefined");

return 0;
}

#include <bits/stdc++.h>
using namespace std;
#define INF 0x7FFFFF

int n;

int main()
{
cin>>n;
vector<string> v;
vector<double> vv;
string s;
while(n--){
cin>>s;
int l=s.size();
int f;
if((s[0]>='0'&&s[0]<='9')||s[0]=='-')
f=1;
else
f=0;

int t=0;
for(int i=1;i<l;i++){
if(s[i]=='.'){
if(t==0)
t=i;
else
f=0;
}
else if(s[i]<'0'||s[i]>'9'){
f=0;
break;
}
}

if(f)
{
if(l-1-t>2&&t!=0)
v.push_back(s);
else
{
double num=0;
if(s[0]=='-')
{
for(int i=1; i<l; i++)
{
if(s[i]!='.')
num=num*10+(s[i]-'0');
}
if(t!=0)
{
num=num*pow(0.1,l-1-t);
}
num=0-num;
}
else
{
for(int i=0; i<l; i++){
if(s[i]!='.')
num=num*10+(s[i]-'0');
}

if(t!=0)
{
num=num*pow(0.1,l-1-t);
}
}
if(num>=-1000&&num<=1000)
vv.push_back(num);
else
v.push_back(s);
}
}
else
v.push_back(s);
}
for(int i=0;i<v.size();i++)
cout<<"ERROR: "<<v[i]<<" is not a legal number"<<endl;
double ave=0;
for(int i=0;i<vv.size();i++){
ave+=vv[i];
}
ave=ave*1.00/(vv.size());
if(vv.size()==1)
printf("The average of 1 number is %.2lf\n",ave);
else if(vv.size()>1)
printf("The average of %d numbers is %.2lf\n",vv.size(),ave);
else
printf("The average of 0 numbers is Undefined\n");

return 0;
}