1054 求平均值 (20 分)

1054 求平均值 (20 分)_第1张图片

#include 
#include
#include
#include
#include
using namespace std;
string str[100];
int n;
bool check(string s) {
    int i = 0;
    if (s[i] == '-')i++;
    for (;s[i] && s[i] != '.';i++) {
        if (!isdigit(s[i])) {//判断字符是否为数字字符
            return false;
        }
    }
    if (s[i] == '.') {
        for (int j = i + 1;s[j];j++) {
            if (!isdigit(s[j]) || j - i > 2) {
                return false;
            }
        }
    }
    double x = fabs(atof(&s[0]));//将字符串转换成浮点数
    if (x > 1000) {
        return false;
    }
    return true;
}
void solve() {
    int count = 0;
    double sum = 0;
    for (int i = 0;i < n;i++) {
        if (check(str[i])) {
            count++;
            sum += atof(&str[i][0]);
        }
        else {
            cout << "ERROR: " << str[i] << " is not a legal number" << endl;
        }
    }
    if (count == 0) {
        cout << "The average of 0 numbers is Undefined" << endl;
    }
    else if (count == 1) {
        printf("The average of 1 number is %.2lf\n", sum);
    }
    else {
        double y = sum / (double)count;
        printf("The average of %d numbers is %.2lf\n", count, y);
    }

}
int main()
{
    cin >> n;
    for (int i = 0;i < n;i++) {
        cin >> str[i];
    }
    solve();
    return 0;
}

参考博客:https://blog.csdn.net/hy971216/article/details/80653566

你可能感兴趣的:(1054 求平均值 (20 分))