0
点赞
收藏
分享

微信扫一扫

PAT乙级:1012 数字分类 (20 分)(Java)


PAT乙级:1012 数字分类 (20 分)(Java)

微信公众号请搜索:【Codeplus】



题目描述:

给定一系列正整数,请按要求对数字进行分类,并输出以下 5 个数字:
A1 = 能被 5 整除的数字中所有偶数的和;
A2 = 将被 5 除后余 1 的数字按给出顺序进行交错求和,即计算 n1 −n2 +n3 −n4 ⋯;
A3 = 被 5 除后余 2 的数字的个数;
A4 = 被 5 除后余 3 的数字的平均数,精确到小数点后 1 位;
A5 = 被 5 除后余 4 的数字中最大数字。

PAT乙级:1012 数字分类 (20 分)(Java)_数据结构

题解思路:
使用取模%运算,if-else语句就可分别执行不同情况的语句,后面的判定如果某一类数字不存在,则在相应的位置输出N,依次判定循环结束得到的数是否满足条件,如果满足输出这个数加空格,如果不满足则输出N加空格(最后一个数的输出不需要空格)

提交代码:

import java.util.Scanner;

/**
* 1012 数字分类 (20 分)
*
* @author LiFeilin
* @date 2021/5/27 11:01
*/
public class Test12 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int number = scanner.nextInt();
int[] array = new int[number];
int A1 = 0, A2 = 0, A3 = 0, A5 = 0;
int sum = 0, count = 0;
int flag = 1;
boolean b = false;

for (int j = 0; j < number; j++) {
array[j] = scanner.nextInt();
if (array[j] % 5 == 0) { //能被 5 整除的数字中所有偶数的和
if (array[j] % 2 == 0)
A1 += array[j];
} else if (array[j] % 5 == 1) { //将被 5 除后余 1 的数字按给出顺序进行交错求和
A2 += (array[j] * flag);
flag = -flag;
b = true;
} else if (array[j] % 5 == 2) { //被 5 除后余 2 的数字的个数
A3++;
} else if (array[j] % 5 == 3) { //被 5 除后余 3 的数字的平均数,精确到小数点后 1 位
sum += array[j];
count++;
} else if (array[j] % 5 == 4) { //被 5 除后余 4 的数字中最大数字
// A5 = array[j];
if (array[j] > A5) {
A5 = array[j];
}
}
}
if (A1 != 0) {
System.out.print(A1 + " ");
} else System.out.print("N ");
if (b) {
System.out.print(A2 + " ");
} else System.out.print("N ");
if (A3 != 0) {
System.out.print(A3 + " ");
} else System.out.print("N ");
if (count != 0) {
System.out.printf("%.1f", (1.0 * sum / count));
System.out.print(" ");
} else System.out.print("N ");
if (A5 != 0) {
System.out.print(A5);
} else System.out.print("N");
}
}

提交结果:

PAT乙级:1012 数字分类 (20 分)(Java)_整除_02



举报

相关推荐

0 条评论