Keshawn_lu's Blog

PAT 1054.求平均值

字数统计: 710阅读时长: 3 min
2021/02/14 Share

题目简介:

本题的基本要求非常简单:给定 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:

1
2
7
5 -3.2 aaa 9999 2.3.4 7.123 2.35

输出样例 1:

1
2
3
4
5
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:

1
2
2
aaa -9999

输出样例 2:

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

思路:

这题烦就烦在要考虑的东西太多了,首先对输入的数字进行判断:

  • 第一位只能是负号或者是数字,否则return false
  • 小数点的个数只能为0或者1个
  • 如果有小数点,那么小数点后的数字最多为两个
  • 数字要在[-1000, 1000]的范围内

满足以上条件的数字才可加入计算中。

tip:

  • 若只有一个符合要求的数字,则需要输出The average of 1 number is ...,注意是number不是numbers

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <unordered_map>
#include <cmath>
#include <iomanip>

using namespace std;

bool judge(string& num) {

if (num[0] != '-' && !isdigit(num[0]))
return false;

if (count(num.begin(), num.end(), '.') > 1) //统计小数点个数
return false;

if (num.find('.') != num.npos) {

if (num.length() - num.find('.') - 1 > 2) //最多精确到小数点后 2 位
return false;
}

if (abs(atof(num.c_str())) > 1000)
return false;

return true;
}

int main()
{
int N;
cin >> N;

double sum = 0;
int valid = 0;
vector<string> wrong;

for (int i = 0; i < N; i++) {

string num;
cin >> num;

if (judge(num)) {

sum += atof(num.c_str());
valid++;
}
else
wrong.push_back(num);
}

for (int i = 0; i < wrong.size(); i++) {

cout << "ERROR: " << wrong[i] << " is not a legal number";

cout << endl;
}


if (valid != 0) {

double average = (double)sum / valid;

if(valid == 1)
cout << "The average of " << valid << " number is ";
else
cout << "The average of " << valid << " numbers is ";

printf("%.2lf", average);
}
else
cout << "The average of " << valid << " numbers is Undefined";
}
CATALOG
  1. 1. 题目简介:
    1. 1.1. 输入格式:
    2. 1.2. 输出格式:
    3. 1.3. 输入样例 1:
    4. 1.4. 输出样例 1:
    5. 1.5. 输入样例 2:
    6. 1.6. 输出样例 2:
  2. 2. 思路:
  3. 3. 代码如下: