排除含有字母、出现一个小数点又有其他非数字字符、小数点后位数超过两位,数的范围在[-1000,1000]之外的情况即可。
//
// main.cpp
// PATA1108
//
// Created by Phoenix on 2018/2/23.
// Copyright © 2018年 Phoenix. All rights reserved.
//
#include <iostream>
#include <cstdio>
#include <cstring>
int main(int argc, const char * argv[]) {
int n, m = 0;
double ans = 0;
scanf("%d ", &n);
for(int i = 0; i < n; i++) {
int j = 0, num1 = 0, num2 = 0, t = 0, a = 0;
char s[100];
scanf("%s", s);
//printf("%s\n", s);
bool flag = true;
int len = strlen(s);
if(s[0] == '-') {
j++;
a = 1;
}
while (j < len) {
while (s[j] >= '0' && s[j] <= '9') {
j++;
num1++;
}
if(s[j] == '.') {
num1++;
t = j + 1;
j++;
while (j < len) {
if(s[j] >= '0' && s[j] <= '9') {
num2++;
}
j++;
}
}
break;
}
//printf("%d %d %d %d\n", a, num1, num2, t);
if(a + num1 + num2 != len) flag = false;
else if(t != 0 && (num2 > 2 || len - t != num2)) flag = false;
else {
double sum = 0;
for(int j = 0; j < len; j++) {
if(s[j] >= '0' && s[j] <= '9') {
sum = sum * 10 + s[j] - '0';
}
}
for(int j = 0; j < num2; j++) sum /= 10;
if(s[0] == '-') sum *= -1;
if(sum >= -1000 && sum <= 1000) {
ans += sum;
m++;
}else {
flag = false;
}
}
if(flag == false) printf("ERROR: %s is not a legal number\n", s);
}
if(m == 0) printf("The average of 0 numbers is Undefined\n");
else if(m == 1) printf("The average of 1 number is %.2f\n", ans);
else printf("The average of %d numbers is %.2f\n", m, ans / m);
return 0;
}