1. 程式人生 > >PAT (Advanced Level) Practice 1108 Finding Average (20 分)

PAT (Advanced Level) Practice 1108 Finding Average (20 分)

#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;

char s[100];
int len;double x;

int check()
{
    for(int i=0;i<len;i++)
    {
        if(s[i]=='-'||s[i]=='.'||'0'<=s[i]&&s[i]<='9') continue;
        else return 0;
    }
    int p=find
(s,s+len,'.')-s; int p1=find(s+p+1,s+len,'.')-s; int p2=find(s,s+len,'-')-s; if(p2!=len&&p2!=0||p2==0&&len==1) return 0; if(p1!=len) return 0; if(len-1-p>2) return 0; sscanf(s,"%lf",&x); if(x<1e3+1e-8&&x>-1e3-1e-8) return 1; return 0; } int
main() { int n;scanf("%d",&n); double ans=0; int num=0; for(int i=1;i<=n;i++) { scanf("%s",s); len=strlen(s); if(check()) ans+=x,num++; else printf("ERROR: %s is not a legal number\n",s); } if(num>1) printf("The average of %d numbers is %.2lf\n"
,num,ans/num); else if(num==1) printf("The average of 1 number is %.2lf\n",ans); else puts("The average of 0 numbers is Undefined"); return 0; }