【PAT B1012】数字分类
题目描述
给定一系列正整数,请按要求对数字进行分类,并输出以下 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
参考代码
#include<cstdio>
#include<cmath>
int main() {
int A1 = 0, A2=0,A3=0, A5=0;
int A1_count = 0, A2_count = 0, A3_count = 0, A4_count = 0, A5_count = 0;
int A2_sum = 0, A4_sum = 0;
int n;
int test[1000];
double A4;
scanf("%d", &n);
for (int i = 0; i < n; i++)
scanf("%d", &test[i]);
int A5_Max = test[0];
for (int i = 0; i < n; i++) {
if (!(test[i] % 5) && !(test[i] % 2)) A1 += test[i], A1_count++;
if (test[i] % 5 == 1) A2_sum += (pow((-1), A2_count)*test[i]),A2_count++;
if (test[i] % 5 == 2) A3_count++;
if (test[i] % 5 == 3) A4_sum += test[i],A4_count++;
if ((test[i] % 5 == 4) && (test[i] > A5_Max)) A5_Max = test[i], A5_count++;
}
if (A1_count == 0)printf("N ");
else printf("%d ", A1);
if (A2_count == 0)printf("N ");
else printf("%d ", A2_sum);
if (A3_count == 0)printf("N ");
else printf("%d ", A3_count);
if (A4_count == 0)printf("N ");
else printf("%.1f ", (double)A4_sum / A4_count);
if (A5_count == 0)printf("N");
else printf("%d", A5_Max);
return 0;
}
运行结果