我以为N比原题多开了一位是要卡我cin、cout,结果被单个负号卡了,原题判定没给这个测试点,佩服。
思路:
分别判断带字母的、小数点超过一个的、小数点一个但是后面超过两位的等非法字符串,合法字符串统计个数,并加到总和里。
代码:
#include <bits/stdc++.h>
using namespace std;
int N, sz = 0;
string s;
double sum = 0;
int main()
{
cin >> N;
for(int i = 0; i < N; i++)
{
cin >> s;
int len = s.length(), cnt = 0, count = 0, flag = 0;
for(int j = 0; j < len; j++)
{
if(s[j] == '-')
{
if(len == 1)
flag = 1;
continue;
}
if(s[j] == '.')
cnt++;
else if(!isdigit(s[j]))
flag = 1;
if(cnt == 1)
count++;
}
if(flag || cnt >= 2 || count > 3)
cout << "ERROR: " << s << " is not a legal number" << endl;
else if(stod(s) < -1000 || stod(s) > 1000)
cout << "ERROR: " << s << " is not a legal number" << endl;
else
{
sz++;
sum += stod(s);
}
}
if(sz > 1)
cout << fixed << setprecision(2) << "The average of " << sz << " numbers is " << sum / sz;
else if(sz == 1)
cout << fixed << setprecision(2) << "The average of " << 1 << " number is " << sum / sz;
else
cout << "The average of 0 numbers is Undefined";
return 0;
}