1108 Finding Average (20分)

 

#include<iostream>
#include<string>
#include<algorithm>
#include<cstdio>

using namespace std;

bool islegal(char a) {
    if (a == '.') return true;
    else if (a >= '0' && a <= '9') return true;
    else return false;
}

bool isnum(string s, double &t) {
    if (s.size() > 8) return false;
    int i = 0, point = -1;
    double total = 0;
    bool neg = false;
    if (s[i] == '-') {
        neg = true;
        i++;
    }
    for (; i < s.size(); i++) {
        if (islegal(s[i]) == false) return false;
        if (point != -1 && i - point >= 3) return false;
        if (s[i] == '.') {
            if (point == -1) {
                point = i;
            }
            else return false;
        }
        else total = total * 10 + s[i] - '0';
    }
    if (point != -1) {
        int dec = i - point - 1;
        while (dec--) {
            total /= 10;
        }
    }
    if (total > 1000) return false;
    if (neg) t = -total;
    else t = total;
    return true;
}

int main() {
    int N;
    int c = 0;
    double total = 0, t = 0;
    scanf("%d", &N);
    string s;
    while (N--) {
        cin >> s;
        if (isnum(s, t)) {
            c++;
            total += t;
        }
        else cout << "ERROR: " << s << " is not a legal number" << endl;
    }
    if (c == 0) {
        cout << "The average of 0 numbers is Undefined" << endl;
    }
    else if (c == 1) {
        cout << "The average of 1 number is ";
        printf("%.2f\n", total / c);
    }
    else {
        cout << "The average of " << c << " numbers is ";
        printf("%.2f\n", total / c);
    }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值