题目描述:
给定一系列正整数,请按要求对数字进行分类,并输出以下5个数字:
A1 = 能被5整除的数字中所有偶数的和;
A2 = 将被5除后余1的数字按给出顺序进行交错求和,即计算n1-n2+n3-n4…;
A3 = 被5除后余2的数字的个数;
A4 = 被5除后余3的数字的平均数,精确到小数点后1位;
A5 = 被5除后余4的数字中最大数字。
思路:
逐条判断,A4稍微复杂点,根据输入例子9.7可判断保留方式为四舍五入,那么可以用BigDecimal的RoudingMode.HALF_UP(表示5进位,DOWN为舍去)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer stringTokenizer = new StringTokenizer(bufferedReader.readLine());
int n = Integer.parseInt(stringTokenizer.nextToken());
int a = 0, b = 0, c = 0, d = 0, e = 0, count = 0;
String[] strings = {"N", "N", "N", "N", "N"};
boolean flag = false; //设立一个标记来切换加减求A2
for (int i = 0; i < n; i++) {
int x = Integer.parseInt(stringTokenizer.nextToken());
if (x % 10 == 0) {
a += x;
}
if (x % 5 == 1) {
if (flag) {
x = -x;
}
b += x;
flag = !flag;
}
if (x % 5 == 2) {
c++;
}
if (x % 5 == 3) {
count++;
d += x;
}
if (x % 5 == 4) {
if (x >= e) {
e = x;
}
}
}
if (a != 0) {
strings[0] = String.valueOf(a);
}
if (b != 0) {
strings[1] = String.valueOf(b);
}
if (c != 0) {
strings[2] = String.valueOf(c);
}
if (d != 0) {
strings[3] = new BigDecimal(d).divide(new BigDecimal(count), 1, RoundingMode.HALF_UP).toString(); //三个参数分别为除数、保留小数位数、保留方式
}
if (e != 0) {
strings[4] = String.valueOf(e);
}
System.out.println(String.join(" ", strings));
bufferedReader.close();
//不关闭流可能会导致返回非零
}
}