1054. 求平均值 (20)
时间限制 400 ms 内存限制 65536 kB 代码长度限制
8000 B 判题程序 Standard 作者 CHEN, Yue
本题的基本要求非常简单:给定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
注意点:对于一个数合法的时候,输出number而不是numbers,,,泪奔…
#define _CRT_SECURE_NO_WARNINGS
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
#include <iomanip>
using namespace std;
#define eps 0.005
bool Judege(string num, double& val) {
val = 0;
bool negetive = false, dot = false; int idx = 0;
double de = 0.1;//用于计算小数点后面的数值
if (num[0] == '-') {
negetive = true;
++idx;
}
while (idx < num.size()) {
if (num[idx] == '.') {
if (!dot) dot = true;
else return false;//非法
}
else if ('0' <= num[idx] && num[idx] <= '9') {
if (!dot) val = val * 10 + num[idx] - '0';
else {
val += (num[idx] - '0') * de;
de /= 10;
if (de <= 0.0001)return false;
}
}
else return false; //非法
++idx;
}
if (negetive)val = -val;
return true;
}
int main() {
#ifdef _DEBUG
freopen("data.txt", "r+", stdin);
#endif // _DEBUG
std::ios::sync_with_stdio(false);
int n, numN = 0; string str;
double sum = 0,num;
cin >> n;
while (n--) {
cin >> str; int valid = true;
bool isnum = Judege(str, num);
if (isnum) {
if (-1000 + -eps < num && num < 1000 + eps) {
++numN;
sum += num;
}
else valid = false;
}
if (!isnum || !valid)cout << "ERROR: " << str << " is not a legal number" << endl;
}
if (numN >= 2)cout << "The average of " << numN << " numbers is " << setiosflags(ios::fixed) << setprecision(2) << sum / numN;
else if (numN == 1)cout << "The average of " << numN << " number is " << setiosflags(ios::fixed) << setprecision(2) << sum / numN;
else cout << "The average of 0 numbers is Undefined";
return 0;
}