Skip to content

1054 求平均值

Statement

Metadata

  • 作者: CHEN, Yue
  • 单位: 浙江大学
  • 代码长度限制: 16 KB
  • 时间限制: 400 ms
  • 内存限制: 64 MB

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

输入格式

输入第一行给出正整数 N\le 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

Solution

#include <bits/stdc++.h>
using namespace std;
int jude(string s) {
    int i, len = s.size(), flag = 0;
    if (s[0] == '-')
        i = 1;
    else
        i = 0;
    for (; i < len; i++) {
        if ((s[i] >= '0' && s[i] <= '9')) {
            continue;
        } else if (s[i] == '.') {
            if (len - i - 1 > 2 || flag)
                return 0;
            else
                flag = 1;
        } else
            return 0;
    }
    if (flag)
        return 2;
    else
        return 1;
}
double tran(string s) {
    while (s[0] == '0') s.erase(0, 1);
    int i, len = s.size(), j = pow(10, len - 1);
    double num = 0;
    for (i = 0; i < len; i++, j /= 10) {
        num += (s[i] - '0') * j;
    }
    return num;
}
double change(string s, int x) {
    int flag = 0;
    if (s[0] == '-') {
        s.erase(0, 1);
        flag = 1;
    }
    int len = s.size(), i, j;
    double num = 0;
    string s1 = "";
    if (x == 1)
        num += tran(s);
    else if (x == 2) {
        for (i = 0; s[i] != '.'; i++) s1 += s[i];
        num += tran(s1);
        s1 = "";
        for (i++, j = 0; i < len; i++, j++) s1 += s[i];
        num += (tran(s1) * pow(0.1, j));
    }
    if (flag)
        num *= -1;
    return num;
}
int main() {
    int n, i, j, total = 0, flag;
    string s;
    cin >> n;
    double tot = 0;
    for (i = 0; i < n; i++) {
        double num;
        flag = 1;
        cin >> s;
        if (jude(s)) {
            num = change(s, jude(s));
            // cout<<num<<endl;
            if (num <= 1000 && num >= -1000)
                total++, tot += num, flag = 0;
        }
        if (flag)
            cout << "ERROR: " << s << " is not a legal number\n";
    }
    if (total > 1)
        printf("The average of %d numbers is %.2lf", total, tot / total);
    else if (total == 1)
        printf("The average of 1 number is %.2lf", tot);
    else
        cout << "The average of 0 numbers is Undefined";
}

Last update: May 4, 2022
Back to top