#include<bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
int n_valid = 0;
double sum = 0;
for(int i = 0; i < n; ++i) {
string tmp;
cin >> tmp;
bool flag = true;
try {
int start = -1;
int cnt = 0;
int len = tmp.length();
int pos;
while((pos=tmp.find('.', start + 1)) != tmp.npos) {
++cnt;
start = pos;
}
if(cnt > 1)
throw exception();
if(cnt && len - start - 1 > 2) {
throw exception();
}
double d = stod(tmp);
if(d > 1000 || d < -1000) {
throw exception();
}
sum += d;
++n_valid;
} catch (exception & e) {
flag = false;
}
if(! flag) {
printf("ERROR: %s is not a legal number\n", tmp.c_str());
}
}
if(n_valid == 0)
printf("The average of 0 numbers is Undefined\n");
else if(n_valid > 1)
printf("The average of %d numbers is %.2f\n", n_valid, sum / n_valid);
else {
printf("The average of 1 number is %.2f\n", sum);
}
}
PAT 1108 Finding Average
最新推荐文章于 2024-07-19 15:45:46 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)