。。。第一眼感觉题目很慌啊,要一个个判断。
然后网上搜了题解,顿时感觉,学到了!
这个是题解的地址:http://www.liuchuo.net/archives/617
用sscanf(a,%lf,&temp)a为字符串char*,temp为double类型的数字。直接将字符串直接转化成数字。
然后因为输出格式没注意。。。wa了几发。。。尴尬
下面是代码
#include <iostream>
#include <cstdio>
#include <string.h>
using namespace std;
int main()
{
int t;
cin>>t;
double temp=0,sum=0.0;
int cnt=0;
while(t--)
{
char s[50];
char a[50];
scanf("%s", s);
sscanf(s,"%lf",&temp);
sprintf(a,"%.2lf",temp);
int flag=0;
for(int i=0;i<strlen(s);i++)
{
if(s[i]!=a[i])
flag=1;
}
if(flag||temp<-1000||temp>1000)
{
printf("ERROR: %s is not a legal number\n",s);
continue;
}
else
{
sum+=temp;
cnt++;
}
}
if(cnt==0)
printf("The average of 0 numbers is Undefined\n");
else if(cnt==1)
printf("The average of 1 number is %.2lf\n",sum);
else
printf("The average of %d numbers is %.2lf\n",cnt,sum*1.0/cnt);
return 0;
}