题意:输入n个字符串,选出合法的数字字符串,求平均值。
思路:ifelse判断一下合法字符就好。
代码
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
const int MAX_N = 10;
char s[MAX_N];
int len, N, t;
double sum;
bool isNum(char s[]) {
len = strlen(s);
int cnt = 1, num = 0;
for (int i = 0; i < len; i++) {
if (cnt == 0) {
num++;
if (num > 2) return false;
}
if (i == 0) {
if (s[i] == '-' && len > 1) continue;
}
if (isdigit(s[i])) continue;
if (s[i] == '.' && cnt > 0) {
cnt--;
} else {
return false;
}
}
return true;
}
int main() {
// freopen("in.txt", "r", stdin);
// freopen("out.txt", "w", stdout);
scanf("%d", &N);
t = 0;
sum = 0.0;
for (int i = 0; i < N; i++) {
scanf("%s", s);
if (isNum(s)) {
double tmp = strtod(s, NULL);
if (tmp < -1000 || tmp > 1000) {
printf("ERROR: %s is not a legal number\n", s);
continue;
}
sum += tmp;
t++;
} else {
printf("ERROR: %s is not a legal number\n", s);
}
}
if (t == 0) {
printf("The average of 0 numbers is Undefined\n");
} else if (t == 1) {
printf("The average of 1 number is %.2lf\n", sum);
} else {
printf("The average of %d numbers is %.2lf\n", t, sum/t);
}
return 0;
}