PAT考试乙级1054(C语言实现) (重点题目)(思路)

#include 
#include 
int legal(char a[]){
    int dot = 0, i = 0, n1 = 0, n2 = 0;
    if(a[0]=='-') i=1;//跳过逗号计算数值
    for(;a[i]!='\0';i++){//下面四句判断的顺序不能改变!!!
        if((a[i]<48||a[i]>57)&&a[i]!='.') return 0;
        if(dot==1&&a[i]=='.') return 0;
        if(dot>0) n1++;
        if(a[i]=='.') dot=1;
        if(dot==0) n2++;
    }
    if (n1 > 2) return 0;
    if (atof(a) < -1000.0 || atof(a) > 1000.0) return 0;

    return 1;
}
int main(){
    int N,c=0,i;
    char select[101]={0};
    double sum=0.0f,ev;
    scanf("%d",&N);
    for(i=0;iscanf("%s",select);
        if(legal(select)){
            sum+=atof(select);
            c++;
        }else
            printf("ERROR: %s is not a legal number\n",select);
    }
    ev=sum/c;
    printf("The average of %d",c);
    if(c==0) printf(" numbers is Undefined");
    if(c==1) printf(" number is %.2lf",ev);
    if(c>=2) printf(" numbers is %.2lf",ev);
    return 0;
}

总结:细节很重要

你可能感兴趣的:(PAT)