星空's Blog
星空's Blog
PAT-A1108 Finding Average

原题

Finding Average (20 分)

题解

蛋疼,最后2个测试点通不过,不知道错在哪
保存一下,会了再改

代码

#include <iostream>
#include <cstdio>
using namespace std;

int main(void) {
    int n,legal = 0;
    double sum; 
    cin >> n;
    for (int i = 0;i < n;i++) {
        string in;
        cin >> in;
        bool isNegative = false;
        bool illegal = false;
        string ori = in;
        //过滤负号
        if (in[0] == '-') {
            isNegative = true;
            in = in.substr(1);
        }
        //小数点位置
        int point = in.find(".");
        //过滤.xx
        if (point == 0) {
            cout << "ERROR: " << ori << " is not a legal number" << endl;
            continue;
        }
        //整数位
        string s1 = in.substr(0,point);
        //浮点位
        string s2 = in.substr(point + 1);

        //过滤其他字符
        for (auto a : s1) {
            if (a < '0' || a > '9') {
                illegal = true;
            }
        }
        //过滤其他字符
        for (auto a : s2) {
            if (a < '0' || a > '9') {
                illegal = true;
            }
        }
        //过滤xx. x.xxx
        if (s2.length() == 0 || s2.length() > 2) {
            illegal = true;
        }
        if (illegal) {
            cout << "ERROR: " << ori << " is not a legal number" << endl;
            continue;
        }
        double real;
        if (point == -1) {
            //整数
            real = stod(s1);
        } else {
            //浮点数
            real = stod(s1 + "." + s2);
        }
        //范围判定
        if (real > 1000) {
            cout << "ERROR: " << ori << " is not a legal number" << endl;
            continue;
        }
        //还原
        if (isNegative) {
            real = -real;
        }
        sum += real;
        legal++;
    }
    if (legal) {
        printf("The average of %d numbers is %.2lf\n",legal,sum / legal);
    } else {
        printf("The average of %d numbers is Undefined\n",legal);
    }
    return 0;
}
所有文章禁止转载。
代码仅供参考
为了对抗广告机器人,首次留言将会被审核
首页      算法学习      PAT-A      PAT-A1108 Finding Average
https://secure.gravatar.com/avatar/271861a23dcdde929d3ee8cb8c04f854?s=256&d=monsterid&r=g

星空

文章作者

发表评论

textsms
account_circle
email

星空's Blog

PAT-A1108 Finding Average
原题 Finding Average (20 分) 题解 蛋疼,最后2个测试点通不过,不知道错在哪 保存一下,会了再改 代码 #include <iostream> #include <cstdio> using namespace std; int …
扫描二维码继续阅读
2019-09-01
分类
标签云