题目描述
blablabla
样例
#include<iostream>
#include<string>
using namespace std;
/**
* 主要是考虑判断是否符合题目要求的数据
*/
double res = 0;
int cnt = 0;
const int N = 1010;
string strs[N];
int main(){
int n;
cin >> n;
// 直接读入字符串
for(int i = 0; i < n; i++) cin >> strs[i];
// 对每个字符串判断合法与否
for(int i = 0; i < n; i++){
auto str = strs[i];
bool is_ok = true;
double cur = 0;
try{
size_t idx;
cur = stof(str, &idx);
// 发生异常以后接下来的语句不会再被执行
// 如果位数不够错误, 如输入的是 12.222ff, 23.1ss
if(idx < str.size()) is_ok = false;
// 判断字符串合法情况下, 但是位数不符合要去 12.222
int k = str.size();
int index = str.find('.');
if(cur > 1000 || cur < -1000) is_ok = false;
if(index > 0 && k - index - 1 > 2) is_ok = false;
}catch(...){ // 字符串不合法错误 抓住所有异常
is_ok = false;
}
// 字符串合法的情况下
if(is_ok){
res += cur;
cnt ++;
}else
{
printf("ERROR: %s is not a legal number\n", str.c_str());
}
}
if(cnt > 1) printf("The average of %d numbers is %.2f\n", cnt, res/cnt);
else if(cnt == 1) printf("The average of 1 number is %.2f\n", res);
else printf("The average of 0 numbers is Undefined\n");
return 0;
}
算法1
(暴力枚举) $O(n^2)$
blablabla
时间复杂度
参考文献
C++ 代码
blablabla
算法2
(暴力枚举) $O(n^2)$
blablabla
时间复杂度
参考文献
C++ 代码
blablabla