传送门
https://pintia.cn/problem-sets/994805260223102976/problems/994805311146147840
题目
给定一系列正整数,请按要求对数字进行分类,并输出以下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
分析
设置5个变量记录符合A1-A5条件的数值,并按需声明变量记录是否存在符合A1-A5的数值,然后按需输出结果即可。
需要注意的就是A2是交错求和与A4精确位数的实现方法。
源代码
//C/C++实现
#include <stdio.h>
#include <iostream>
#include <math.h>
using namespace std;
int main(){
int n, num;
int a1 = 0, a2 = 0, a3 = 0, a4 = 0, a5 = 0;
bool existA1 = false, existA2 = false;
int countA4 = 0;
scanf("%d", &n);
for(int i = 0, j = 0; i < n; i++){
scanf("%d", &num);
if(num % 5 == 0){
if(num % 2 == 0){
existA1 = true;
a1 += num;
}
}
else if(num % 5 == 1){
existA2 = true;
a2 += num * pow((double)(-1), j);
j++;
}
else if(num % 5 == 2){
a3++;
}
else if(num % 5 == 3){
a4 += num;
countA4++;
}
else{
a5 = (num > a5 ? num : a5);
}
}
if(existA1){
printf("%d", a1);
}
else{
printf("%c", 'N');
}
if(existA2){
printf(" %d", a2);
}
else{
printf(" %c", 'N');
}
if(a3 != 0){
printf(" %d", a3);
}
else{
printf(" %c", 'N');
}
if(countA4 != 0){
printf(" %.1f", (double)a4 / countA4);
}
else{
printf(" %c", 'N');
}
if(a5 != 0){
printf(" %d\n", a5);
}
else{
printf(" %c\n", 'N');
}
return 0;
}
//Java实现
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws Exception {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
String s = bufferedReader.readLine();
String[] arrayS = s.split(" ");
int capacity = 0;
try {
capacity = Integer.valueOf(arrayS[0]);
} catch (Exception e) {
System.exit(0);
}
if (capacity < 1 || capacity > 1000) {
System.exit(0);
}
int tmp = 0;
int A1 = 0, A2 = 0, A3 = 0, A5 = 0, countA4 = 0, sumA4 = 0, j = 0;
boolean existA2 = false;
for (int i = 0; i < capacity; i++) {
try {
tmp = Integer.valueOf(arrayS[i+1]);
} catch (Exception e) {
System.exit(0);
}
if (tmp < 1 || tmp > 1000) {
System.exit(0);
}
if (tmp % 10 == 0) {
A1 += tmp;
} else if (tmp % 5 == 1) {
A2 += tmp * (int) Math.pow(-1, j);
existA2 = true;
j++;
} else if (tmp % 5 == 2) {
A3++;
} else if (tmp % 5 == 3) {
sumA4 += tmp;
countA4++;
} else if (tmp % 5 == 4) {
A5 = A5 > tmp ? A5 : tmp;
}
}
if (A1 != 0) {
System.out.print(A1 + " ");
} else {
System.out.print("N ");
}
if (existA2) {
System.out.print(A2 + " ");
} else {
System.out.print("N ");
}
if (A3 != 0) {
System.out.print(A3 + " ");
} else {
System.out.print("N ");
}
if (countA4 != 0) {
double avg = (double) sumA4 / countA4;
System.out.print(Math.round(avg * 10) / 10.0 + " ");
} else {
System.out.print("N ");
}
if (A5 != 0) {
System.out.println(A5);
} else {
System.out.println("N");
}
}
}