xx.也是合法数字…
#include<iostream>
#include<string>
#include<cctype>
#include<cmath>
using namespace std;
int main() {
int n;
cin >> n;
double sum = 0;
int count = 0;
for (int i = 0;i < n;i++) {
string temp;
cin >> temp;
int decimalPlace = -1;
bool legal = true;
for (int j = 0;j < temp.length();j++) {
if (j == 0 && temp[j] == '-' && temp.length() > 1) {
continue;
}
if (temp[j] != '.' && !isdigit(temp[j])) {
legal = false;
break;
}
else if (temp[j] == '.') { //xx.也是合法数字??
if (decimalPlace != -1 || j == 0) {
legal = false;
break;
}
else decimalPlace = j;
}
}
int accuracy = 0;
if (decimalPlace != -1) {
accuracy = temp.length() - decimalPlace - 1;
}
if (!legal || decimalPlace != -1 && accuracy > 2 || temp.length() - accuracy > 6 || abs(stod(temp)) > 1000) {
cout << "ERROR: " << temp << " is not a legal number" << endl;
}
else {
sum += stod(temp);
count++;
}
}
if (count == 1) {
printf("The average of %d number is ", count);
}
else printf("The average of %d numbers is ", count);
if (count > 0) {
printf("%.2lf", sum / count);
}
else printf("Undefined");
}
二刷:
不逐个判断不合法的情况,而是只允许合法的情况通过,避免了要逐一排除各种不合法的情况。
#include<iostream>
#include<string>
#include<cctype>
using namespace std;
int main() {
int n;
cin >> n;
double sum = 0;
int count = 0;
for (int i = 0; i < n; i++) {
string s;
cin >> s;
bool isLegal = true;
int pointIndex = s.find('.');
if (pointIndex != -1 && s.length() - pointIndex - 1 > 2) {
isLegal = false;
}
bool hasDigit = false;
for (int j = 0; j < s.length(); j++) {
//如果输入合法,则继续判断,而不逐个排除不合法输入
if (j == 0 && s[j] == '-') {
continue;
}
if (s[j] == '.' && j == pointIndex) {
continue;
}
if (isdigit(s[j])) {
hasDigit = true;
continue;
}
isLegal = false;
break;
}
if (!hasDigit) { //避免 -. 和 -
isLegal = false;
}
if (isLegal) {
double num = stod(s);
if (num >= -1000 && num <= 1000) {
sum += num;
++count;
}
else {
isLegal = false;
}
}
if (!isLegal) {
printf("ERROR: %s is not a legal number\n", s.c_str());
}
}
if (count == 0) {
printf("The average of 0 numbers is Undefined\n");
}
else if (count == 1) {
printf("The average of 1 number is %.2lf", sum / count);
}
else {
printf("The average of %d numbers is %.2lf\n", count, sum / count);
}
}