我的个人网站 Cheese的个人主页http://www.cheese.ren/
博客来源 http://blog.cheese.ren/74http://blog.cheese.ren/74
欢迎交换友链 :-)
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, length, vaild_n=0;
string s;
double sum=0, temp;
bool flag;
cin >> n;
while (n--) {
flag = true;
cin >> s;
// 第一位只能是数字或'-'
if (s[0] != '-' && (s[0] > '9' || s[0] < '0')) {
cout << "ERROR: " << s << " is not a legal number" << endl;
continue;
}
// 只输入'-'
if (s[0] == '-' && s.length() == 1) {
cout << "ERROR: " << s << " is not a legal number" << endl;
continue;
}
// 遍历字符串
length = -1;
for (int i=1; i<s.length(); i++) {
// 不能有数字和小数点以外的字符
if (s[i] != '.' && (s[i] > '9' || s[i] < '0')) {
cout << "ERROR: " << s << " is not a legal number" << endl;
flag = false;
break;
}
// 计算精度长度
if (length != -1) {
length++;
if (length > 2) {
cout << "ERROR: " << s << " is not a legal number" << endl;
flag = false;
break;
}
}
// 小数点只能出现一次,并且不能是最后一位,如果第一位是负号,第二位不能是小数点
if (s[i] == '.') {
if (length == -1 || i != s.length()-1 || (i == 1 && s[0] == '-')) {
length++;
}
else {
cout << "ERROR: " << s << " is not a legal number" << endl;
flag = false;
break;
}
}
}
if (!flag) {
continue;
}
// 大范围
temp = atof(s.c_str());
if (temp > 1000 || temp < -1000) {
cout << "ERROR: " << s << " is not a legal number" << endl;
continue;
}
vaild_n++;
sum += temp;
}
if (vaild_n == 0) {
cout << "The average of 0 numbers is Undefined" << endl;
}
else {
if (vaild_n == 1) {
cout << fixed << setprecision(2) << "The average of " << vaild_n << " number is " << sum/vaild_n << endl;
}
else {
cout << fixed << setprecision(2) << "The average of " << vaild_n << " numbers is " << sum/vaild_n << endl;
}
}
return 0;
}