65,206
社区成员
发帖
与我相关
我的任务
分享#include <iostream>
#include <string>
using namespace std;
int main() {
int N, count = 0;
double sum = 0;
cin >> N;
while (N--) {
string A;
cin >> A;
try { //判断是否能转换为float类型,若不能则进行异常处理
float a = stof(A);
//判断合法区间[-1000,1000] || 判断精度 ||判断转换为浮点型的字符串是否是原来的字符串(像2.2a会被转换成2.20000....,且不会报错)
if (a < -1000 || a>1000 || A.size() - A.find('.') > 3 || to_string(a).compare(0, A.size(), A) != 0) {
cout << "ERROR: " << A << " is not a legal number" << endl;
continue;
}
count++;
sum += a;
}
catch (...) {
cout << "ERROR: " << A << " is not a legal number" << endl;
}
}
if (!count)
cout << "The average of 0 numbers is Undefined" << endl;
else if (count == 1) //测试点2
printf("The average of 1 number is %.2f\n", sum);
else
printf("The average of %d numbers is %.2f\n", count, sum / count);
return 0;
}
if (a < -1000 || a>1000
|| A.find('.') != string::npos && A.size() - A.find('.') > 3
|| to_string(a).compare(0, A.size(), A) != 0)