PAT甲题题解-1108. Finding Average (20)-字符串处理

求给出数的平均数,当然有些是不符合格式的,要输出该数不是合法的。

这里我写了函数来判断是否符合题目要求的数字,有点麻烦。

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <string.h>
using namespace std;
const int maxn=105;

bool islegal(char*str){
    int len=strlen(str);
    int point=0,decimal=0;
    for(int i=0;i<len;i++){
        //if(i==0 && str[i]=='0'&&len>1){
        //    if(str[1]!='.')
        //        return false;
        //}
        if(str[i]=='-' && i!=0)
            return false;
        else if(str[i]=='-' && i==0)
            continue;
        if(str[i]=='.' && i==0)
            return false;
        if(str[i]=='.'){
            point++;
            if(point>=2)
                return false;
        }
        else if(str[i]<'0' ||str[i]>'9')
            return false;
        else if(str[i]>='0' && str[i]<='9' && point==1){
            decimal++;
            if(decimal>=3)
                return false;
        }
    }
    return true;
}

int main()
{
    int n;
    char str[maxn];
    scanf("%d",&n);
    double sum=0.0;
    double a;
    int k=0;
    for(int i=0;i<n;i++){
        scanf("%s",str);
        bool flag=false;
        if(islegal(str)){
            a=atof(str);
            if(a>=-1000.0 && a<=1000.0)
                flag=true;
        }
        if(flag){
//printf("%lf
",a);
            sum+=a;
            k++;
        }
        else{
            printf("ERROR: %s is not a legal number
",str);
        }
    }
    if(k==0){
        printf("The average of 0 numbers is Undefined
");
    }
    else if(k==1){
        printf("The average of %d number is %.2lf
",k,sum);
    }
    else{
        printf("The average of %d numbers is %.2lf
",k,sum/k);
    }
    return 0;
}
View Code

可以参考下面别人的题解,用到了sscanf和sprintf函数,就很方便:

http://www.liuchuo.net/archives/1924

原文地址:https://www.cnblogs.com/chenxiwenruo/p/6390188.html