给定一系列正整数,请按要求对数字进行分类,并输出以下 5 个数字:
- A1 = 能被 5 整除的数字中所有偶数的和;
- A2 = 将被 5 除后余 1 的数字按给出顺序进行交错求和,即计算 n1−n2+n3−n4⋯;
- A3 = 被 5 除后余 2 的数字的个数;
- A4 = 被 5 除后余 3 的数字的平均数,精确到小数点后 1 位;
- A5 = 被 5 除后余 4 的数字中最大数字。
输入格式:
每个输入包含 1 个测试用例。每个测试用例先给出一个不超过 1000 的正整数 N,随后给出 N 个不超过 1000 的待分类的正整数。数字间以空格分隔。
输出格式:
对给定的 N 个正整数,按题目要求计算 A1~A5 并在一行中顺序输出。数字间以空格分隔,但行末不得有多余空格。
若其中某一类数字不存在,则在相应位置输出 N
。
输入样例 1:
13 1 2 3 4 5 6 7 8 9 10 20 16 18
输出样例 1:
30 11 2 9.7 9
输入样例 2:
8 1 2 4 5 6 7 9 16
输出样例 2:
N 11 2 N 9
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int N = input.nextInt();//输入N个数字
int[] arr = new int[N];
for(int i = 0;i<arr.length;i++) {
arr[i] = input.nextInt();
}
int temp = 0;
int pow = 0;
int index = 0;//指数
float[] numArr = new float[5];//开拓浮点型数组
for(int i = 0;i<arr.length;i++) {
temp = arr[i];//确定一个数来咱是保存数组对应的数值
if(temp%5==0&&temp%2 == 0) {
numArr[0] += temp;
}
if(temp%5 == 1) {
numArr[1] += ((int)Math.pow(-1, pow)*temp);//Math.pow(x,y)pow()方法可返回 x 的 y 次幂的值。
pow++;
}
if(temp%5==2) {
numArr[2]++;
}
if(temp%5==3) {
index++;
numArr[3] += temp;
}
if(temp%5==4) {
temp = arr[0];
if(temp>arr[i]) {
numArr[4] = temp;
}else {
numArr[4] = arr[i];
}
}
}
for(int i = 0;i<5;i++) {
if(i == 4) {
if(numArr[4] == 0) {
System.out.print("N");//有空格
}else {
System.out.print((int)numArr[i]);//输出整数
}
}else if(i == 3) {
if(numArr[3] == 0) {
System.out.print("N ");//有空格
}else {
System.out.print(String.format("%.1f",(numArr[i] / index)) + " ");
}
//String类的format()方法用于创建格式化的字符串以及连接多个字符串对象 String.format()
//格式化字符串的意思是使用Format函数将指定的字符串转换为想要的输出格式
if(i==1&&pow>0) {
if(numArr[i] == 0) {
System.out.print((int)numArr[i] + " ");
}
}
}else if(numArr[i] == 0) {
System.out.print("N ");
}else {
System.out.print((int)numArr[i] + " ");
}
}
}
}
//A1= 能被 5 整除的数字中所有偶数的和;
//A2= 将被 5 除后余 1 的数字按给出顺序进行交错求和,即计算 n1−n2+n3−n4⋯;(出错,如果相减得
0,不能返回N,4 6 11 21 16 输不出0)
//A3= 被 5 除后余 2 的数字的个数;
//A4= 被 5 除后余 3 的数字的平均数,精确到小数点后 1 位;
//A5= 被 5 除后余 4 的数字中最大数字。