PAT成长之路——1054 求平均值 (20 分)

版权声明:有善始者实繁,能克终者盖寡。 https://blog.csdn.net/weixin_43987810/article/details/87068295

题目:

1054 求平均值 (20 分)

本题的基本要求非常简单:给定 N 个实数,计算它们的平均值。但复杂的是有些输入数据可能是非法的。一个“合法”的输入是 [−1000,1000] 区间内的实数,并且最多精确到小数点后 2 位。当你计算平均值的时候,不能把那些非法的数据算在内。

输入格式:

输入第一行给出正整数 N(≤100)。随后一行给出 N 个实数,数字间以一个空格分隔。

输出格式:

对每个非法输入,在一行中输出 ERROR: X is not a legal number,其中 X 是输入。最后在一行中输出结果:The average of K numbers is Y,其中 K 是合法输入的个数,Y 是它们的平均值,精确到小数点后 2 位。如果平均值无法计算,则用 Undefined 替换 Y。如果 K 为 1,则输出 The average of 1 number is Y

输入样例 1:

7
5 -3.2 aaa 9999 2.3.4 7.123 2.35

输出样例 1:

ERROR: aaa is not a legal number
ERROR: 9999 is not a legal number
ERROR: 2.3.4 is not a legal number
ERROR: 7.123 is not a legal number
The average of 3 numbers is 1.38

输入样例 2:

2
aaa -9999

输出样例 2:

ERROR: aaa is not a legal number
ERROR: -9999 is not a legal number
The average of 0 numbers is Undefined

分析: 

本题是一个判断输入的数字是否合法的题目,我之前尝试过很多方法(都是分类讨论)(已经自闭了一下午...),讨论小数点的个数,是否有符号,是否有非法字符等等,后来提交上去总是不能AC, 原因就是每次讨论都会拉下几个特殊要点。后来在别人的博客里面找到了一个极其简洁的方法(其方法的可行性是可以通过讨论不同情况验证的)。

题解代码:

#include <cstdio>
#include <iostream>
using namespace std;
int cnt;
double sum;
int judge(char s[]);          //自定义的判断函数

int main()
{
    int N;
    char s[100];

    cin >> N;
    while(N--)
    {
        cin >> s;
        if(!judge(s))
            printf("ERROR: %s is not a legal number\n", s);
    }
    if(!cnt)
        printf("The average of 0 numbers is Undefined\n");
    else printf("The average of %d %s is %.2lf\n", cnt, cnt == 1 ? "number" : "numbers", sum / cnt);       //最后一个测试点

    return 0;
}

int judge(char s[])
{
    int i;
    double a;
    char temp[100];
    int flag = 0;

    sscanf(s, "%lf", &a);            //学习sscanf的用法
    sprintf(temp, "%.2lf", a);        //学习sprintf的用法
    for(i = 0; s[i] != '\0'; i++)       //这里只需扫描源字符串即可,因为当源字符串有非法字符,转换以后一定temp里面一定没有该字符(多了小数点、有+、有前导0也是);另外如果s保留了小数点3位及以上或少于2位,转换之后的temp里面一定只有两位,均能判断s的合法性;
        if(s[i] != temp[i])
            return 0;
    if(a > 1000 || a < -1000)
        return 0;
    sum += a, cnt++;
    return 1;
}

 

猜你喜欢

转载自blog.csdn.net/weixin_43987810/article/details/87068295
今日推荐