PAT A1108 Finding Average ——和羞走,倚门回首,却把青梅嗅

PAT A1108 Finding Average

  • 这里的判断只做了一些基本的限制(正负号、每一位是不是数字、小数点的位置和数字的范围),还好测试用例也没有过于丰富的想象
  • 需要注意当有效的数字个数为0和1时的特殊输出
  • 看了柳神的方法,用sscan后sprintf回来的进行比较,省去了好多麻烦
  • 在这里插入图片描述

#include<iostream>
#include<string>

using namespace std;


int main(){

    int num;
    cin >> num;
    int err_cnt = 0;
    double total = 0.0;
    for(int i = 0;i < num;i ++){
        string tmp;
        cin >> tmp;
        int j = 0,pos = -1;
        for(;j < tmp.length();j ++){
            if(j == 0 && tmp[j] == '-') continue;
            if((tmp[j] < '0' || tmp[j] > '9') && tmp[j] != '.'){
                cout << "ERROR: " + tmp + " is not a legal number\n";
                err_cnt ++;
                break;
            }
            if(pos == -1 && tmp[j] == '.') pos = j;
        }
        if(j != tmp.length()) continue;
        if(pos != -1 && tmp.length() - pos > 3){
            cout << "ERROR: " + tmp + " is not a legal number\n";
            err_cnt ++;
            continue;
        }
        double val = stod(tmp);
        if(val < -1000 || val > 1000){
            cout << "ERROR: " + tmp + " is not a legal number\n";
            err_cnt ++;
            continue;
        }
        total += val;
    }
    if(num - err_cnt == 1) printf("The average of 1 number is %.2lf",total);
    else if(num - err_cnt) printf("The average of %d numbers is %.2lf",num - err_cnt,total / (num - err_cnt));
    else printf("The average of 0 numbers is Undefined");
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值