PAT B1012.数字分类

来源:互联网 发布:ssohandler java 编辑:程序博客网 时间:2024/06/06 01:05
给定一系列正整数,请按要求对数字进行分类,并输出以下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<iostream>using namespace std;int main() {int result[5] = { 0 };int flag[5] = { 0 };//reverse用来进行交错求和int reverse = 1,n,count=0,temp;cin >> n;for (int i = 0; i < n; i++) {cin >> temp;switch (temp % 5) {case 0: {if (!(temp % 10)) {result[0] += temp;flag[0] = 1;}break;}case 1: {result[1] += reverse*temp;reverse *= -1;flag[1] = 1;break;}case 2: {result[2]++;flag[2] = 1;break;}case 3: {count++;result[3] += temp;flag[3] = 1;break;}case 4: {if (temp > result[4]) {result[4] = temp;flag[4] = 1;}break;}}}if (!flag[0])  cout << "N ";else  cout << result[0] << " ";if (!flag[1])   cout << "N ";else  cout << result[1] << " ";if (!flag[2])  cout << "N ";else  cout << result[2] << " ";if (!flag[3])  cout << "N ";else  printf("%.1f ", (double)result[3] / count);if (!flag[4])  cout << "N";else  cout << result[4];return 0;}//注意//1.行末不得有多余空格。//2.必须开一个标志的数组,单独使用结果为0来判断可能出现相加为0但实际存在该类数字而输出错误//!运算符比%优先级高  故temp%10==0不能写成!temp%10