在网上查了一下,发现没有用正则表达式来求解此题的。于是我使用了C++的regex_march匹配合法的字符串。
不做不要紧,一做下去发现有个巨坑。
首先,考虑正常情况,形如1000.00、-999.99、0.1等都是合法的,因此很容易得出此正则表达式为:
-?(1000(\.0{0,2})?|\d{1,3}(\.\d{1,2})?)
使用上述正则表达式时,发现测试点4总是通不过。上网查阅资料才发现,原来是测试点4认为形如123.也是合法的(.12有待查证,-.12也是非法的),此为坑。
遂将上述正则表达式改为
-?(1000(\.0{0,2})?|\d{1,3}(\.\d{0,2})?)|\.\d{1,2}
于是通过。完全源码如下:
#include <bits/stdc++.h>
using namespace std;
int main() {
wint_t N, K = 0;
string X;
double Y = 0;
cin >> N;
for (wint_t n = 0; n < N; ++n) {
cin >> X;
if (regex_match(X, regex(R"(-?(1000(\.0{0,2})?|\d{1,3}(\.\d{0,2})?)|\.\d{1,2})"))) {
Y += stod(X);
++K;
}
else cout << "ERROR: " << X << " is not a legal number" << endl;
}
if (K > 1)cout << "The average of " << K << " numbers is " << setiosflags(ios::fixed) << setprecision(2) << Y / K;
else if (K == 1)cout << "The average of 1 number is " << setiosflags(ios::fixed) << setprecision(2) << Y;
else cout << "The average of 0 numbers is Undefined";
}