The basic task is simple: given N real numbers, you are supposed to calculate their average. But what makes it complicated is that some of the input numbers might not be legal. A legal input is a real number in [−1000,1000] and is accurate up to no more than 2 decimal places. When you calculate the average, those illegal numbers must not be counted in.
Input Specification:
Each input file contains one test case. For each case, the first line gives a positive integer N (≤100). Then N numbers are given in the next line, separated by one space.
Output Specification:
For each illegal input number, print in a line ERROR: X is not a legal number
where X
is the input. Then finally print in a line the result: The average of K numbers is Y
where K
is the number of legal inputs and Y
is their average, accurate to 2 decimal places. In case the average cannot be calculated, output Undefined
instead of Y
. In case K
is only 1, output The average of 1 number is Y
instead.
Sample Input 1:
7
5 -3.2 aaa 9999 2.3.4 7.123 2.35
Sample Output 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
Sample Input 2:
2
aaa -9999
Sample Output 2:
ERROR: aaa is not a legal number
ERROR: -9999 is not a legal number
The average of 0 numbers is Undefined
Ω
输入一个数组,对不合法的数字进行报错输出,然后对所有合法的数字求取平均值。
总体来说并不是很难,主要是题目没看全就要了老命。首先,没有合法数字的话最后的平均值应为Undefined,如果只有一个合法数字的话必须number而非numbers。其他就是对数字合法性的检验了,大概有以下几点:
小数点个数
夹杂非数字字符
小数点后的位数不超过两位
整体数值的绝对值不>1000
我对于小数点最多精确到两位的理解就是小数点后只能有两位,而整数部分可以有前置0。那么先以字符串的形式读入,然后遍历所有字符,逐一判断是否为小数点(之前是否出现过)、非数字字符、小数点前有效数字位数是否<5、小数点后位数是否<3。
🐎
#include <iostream>
using namespace std;
int main()
{
int n, cnt = 0;
cin >> n;
string t;
double sum = 0;
for (int i = 0; i < n; ++i)
{
cin >> t;
int before = 0, after = 0;
bool flag = true, point = false, sign = t[0] == '-' && (t.erase(0, 1), true);
for (auto &c: t)
{
if (c == '.' && !point)
{
point = true;
continue;
}
else if (!isdigit(c))
flag = false;
else if (!point)
flag = (before += (before != 0 || c != '0')) < 5;
else
flag = ++after < 3;
if (!flag) break;
}
if (flag && stod(t) <= 1000)
{
sum += (sign ? -1 : 1) * stod(t);
cnt += 1;
}
else
{
t = (sign ? "-" : "") + t;
printf("ERROR: %s is not a legal number\n", t.c_str());
}
}
if (!cnt) printf("The average of 0 numbers is Undefined");
else printf("The average of %d number%s is %.2f", cnt, cnt == 1 ? "" : "s", sum / cnt);
}