Day014 PAT乙级 1012 数字分类

PAT乙级 1012 数字分类

题目

分析

  1. 题目要求将输入的数字按不同的规则分为5类,最终按照要求输出符合的数字,如果没有符合要求的数字则输出 N
  2. 首先定义一个变量n用来决定输入几个数字,然后使用for循环,每循环一次输入一个数字,循环中使用if else进行判断
  3. 由于需要记录符合要求的数字,还要记录符合要求的数字是否存在过,所以这里可以使用二维数组存储数字,第一列用来记录结果,第二列用来判断是否存在,数组下标则表示是第几类的数字
  4. 当有符合要求的数字时,将其保存至 a[i][0] ,同时 a[i][1]+1 表示存在符合要求的数
  5. 最终再使用一个for循环,先判断 a[i][1] 是否等于0,如果是则输出 a[i][0] ,否则输出 N

代码

import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner cin = new Scanner(System.in);
        int n = cin.nextInt();
        int[][] a = new int[5][2];
        int flag = 1;
        int count = 0;
        for (int i = 0; i < n; i++) {
            int x = cin.nextInt();
            if (x % 10 == 0) {		//判断A1
                a[0][0] += x;
                ++a[0][1];
            } else if (x % 5 == 1) {	//判断A2
                a[1][0] += x * flag;
                ++a[1][1];
                flag *= -1;
            } else if (x % 5 == 2) {	//判断A3
                ++a[2][0];
                ++a[2][1];
            } else if (x % 5 == 3) {	//判断A4
                a[3][0] += x;
                ++a[3][1];
                ++count;
            } else if (x % 5 == 4 && a[4][0] < x) {//判断A5
                a[4][0] = x;
                ++a[4][1];
            }
        }
        for (int i = 0; i < 5; i++) {
            if (i != 0) System.out.print(" ");
            if (a[i][1] == 0) System.out.print("N");
            else if (i == 3) System.out.printf("%.1f", (double) a[3][0] / count);//A4要保留一位小数
            else System.out.print(a[i][0]);
        }
        cin.close();
    }
}
原文地址:https://www.cnblogs.com/mooncell/p/14825659.html