描述
給定一系列正整數(shù),請按要求對數(shù)字進行分類蹭秋,并輸出以下5個數(shù)字:
- A1 = 能被5整除的數(shù)字中所有偶數(shù)的和;
- A2 = 將被5除后余1的數(shù)字按給出順序進行交錯求和仁讨,即計算n1-n2+n3-n4...粒督;
- A3 = 被5除后余2的數(shù)字的個數(shù);
- A4 = 被5除后余3的數(shù)字的平均數(shù)屠橄,精確到小數(shù)點后1位;
- A5 = 被5除后余4的數(shù)字中最大數(shù)字锐墙。
輸入格式:
每個輸入包含1個測試用例。每個測試用例先給出一個不超過1000的正整數(shù)N溪北,隨后給出N個不超過1000的待分類的正整數(shù)夺脾。數(shù)字間以空格分隔茉继。
輸出格式:
對給定的N個正整數(shù)咧叭,按題目要求計算A1~A5并在一行中順序輸出烁竭。數(shù)字間以空格分隔,但行末不得有多余空格派撕。
若其中某一類數(shù)字不存在,則在相應(yīng)位置輸出“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 可以被 5 整除, 但 5 不是偶數(shù)际跪, 所以a類數(shù)字不存在 )
思路:先將數(shù)字讀入并按整除 5 后的余數(shù)作為分組依據(jù),分別存入五個數(shù)組垫卤,然后分別遍歷五個數(shù)組威彰,按題目要求對數(shù)組內(nèi)的元素進行統(tǒng)計或計算。
C語言
#include <stdio.h>
int main(void)
{
int n;
scanf("%d", &n);
int a1[n], a2[n], a3[n], a4[n], a5[n];
int cnt1=0, cnt2=0, cnt3=0, cnt4=0, cnt5=0;
int num;
while (n--){
scanf("%d", &num);
// printf("%d mod %d = %d\n", num, 5, num % 5);
switch (num%5) { // 將各類數(shù)字分別放入不同數(shù)組中
case 0:
if (num % 2 == 0){
a1[cnt1++] = num;
}
break;
case 1:
a2[cnt2++] = num;
break;
case 2:
a3[cnt3++] = num;
break;
case 3:
a4[cnt4++] = num;
break;
case 4:
a5[cnt5++] = num;
}
}
// 按題目要求對各類數(shù)字進行處理
int i;
int result;
for (i=0, result=0; i<cnt1; i++){
if (a1[i] % 2 == 0){
result += a1[i];
}
}
if (cnt1 == 0){
printf("N ");
} else {
printf("%d ", result);
}
int flag = 1;
for (i=0, result=0; i<cnt2; i++){
result += flag * a2[i];
flag *= -1;
}
if (cnt2 == 0){
printf("N ");
} else {
printf("%d ", result);
}
if (cnt3 == 0){
printf("N ");
} else {
printf("%d ", cnt3);
}
for (i=0, result=0; i<cnt4; i++){
result += a4[i];
}
if (cnt4 == 0){
printf("N ");
} else {
printf("%.1f ", result/(double)cnt4);
}
for (i=0, result=a5[0]; i<cnt5; i++){
if (result < a5[i]){
result = a5[i];
}
}
if (cnt5 == 0){
printf("N");
} else {
printf("%d", result);
}
return 0;
}