PAT乙类1054 求平均值 JAVA代码

public static void main(String[] args) throws IOException {

        //下面这个正则会认为  ’-‘和'+'为数字
        Pattern pattern = Pattern.compile("^[-+]?(([0-9]+)([.]([0-9]+))?|([.]([0-9]+))?)$");

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int N = Integer.parseInt(br.readLine());
        String[] split = br.readLine().split("\\s+");
        double res = 0.0;
        int x = 0;
        for (int i = 0; i < split.length; i++) {
            //关于123.这样的数字pat认为合法
            if (split[i].contains(".")&&split[i].split("\\.").length==1){
                split[i] = split[i].split("\\.")[0];
            }
            if (!pattern.matcher(split[i]).matches() || split[i].equals("-") || split[i].equals("+")) {
                System.out.println("ERROR: " + split[i] + " is not a legal number");
            } else {
                if (Double.parseDouble(split[i]) > 1000.0 || Double.parseDouble(split[i]) < -1000.0) {
                    System.out.println("ERROR: " + split[i] + " is not a legal number");
                } else {

                    if (/*精度问题————有小数点则判断小数点后是否小于等于2*/ split[i].contains(".")) {
                        if (split[i].split("\\.")[1].length() > 2) {
                            System.out.println("ERROR: " + split[i] + " is not a legal number");
                        } else {
                            x++;
                            res += Double.parseDouble(split[i]);
                        }
                    }else {
                        x++;
                        res += Double.parseDouble(split[i]);
                    }

                }
            }
        }
        DecimalFormat df=new DecimalFormat("0.00");
        if (x != 0) {
            if (x == 1){
                res /= x;
                System.out.println("The average of " + x + " number is " + df.format(res));
            }else {
                res /= x;
                System.out.println("The average of " + x + " numbers is " + df.format(res));
            }
        } else {
            System.out.println("The average of 0 numbers is Undefined");
        }
    }

测试点0、1是输入案例

测试点2是K为1的情况

测试点3是123.的情况(pat认为这个数字合法)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值