1054 求平均值 (20 分)
分析:这个题乍一看并不难,但是丢分的点还是挺多的。
1.要注意只有一个小数点
2.小数点不能放在首位,而且首位是负号的话不能只有这一位。
3.每位只能是数字,且小数点后只有两位,并且总的绝对值小于1000.
4.输出的时候注意如果只有一个数为正确的 是 number 如果是两个及以上 是numbers(注意审题)
代码如下:
#include<string>
#include<cmath>
using namespace std;
int pd(string s) {
int key = 0; //记录小数点
int m = 0; //记录小数位数
if (!(s[0] == '-'&&s.length()>1) && !isdigit(s[0])) //第一位必为数字或者负号(不能只有负号)
return 0;
for (int i = 1; i < s.length(); i++) {
if (isdigit(s[i])) {
if (key) m++; //小数位计数器
}
else if (s[i] == '.') {
key++; //开启计数器
if (key == 2) //只能有一个小数点
return 0;
}
else //出现其他符号返回0
return 0;
}
if (m <= 2 && abs(atof(s.c_str())) <= 1000) //必须保证在题目范围内
return 1;
return 0;
}
int main() {
int n, count = 0;
double t, sum = 0;
string str;
cin >> n;
while (n--) {
cin >> str;
if (pd(str)) {
count++;
sum += atof(str.c_str());
}
else {
cout << "ERROR: " << str << " is not a legal number" << endl;
}
}
cout << "The average of " << count;
if (count == 1) //看清题意
cout << " number is ";
else
cout << " numbers is ";
if (count)
printf("%0.2lf", (double)sum / count);
else
cout << "Undefined";
return 0;
}