1012 数字分类 (20分)

给定一系列正整数,请按要求对数字进行分类,并输出以下 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

代码

// 1012 数字分类.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。

#include <iostream>
#include<cstdio>
using namespace std;

int main()
{
	int ans1 = 0;//以0结尾的数字的和
	int ans2_flag = 0;//确定数字的系数,0正1负
	int ans2 = 0;
	int ans2_count = 0;
	int ans3 = 0;//除5余2的个数
	int ans4_sum = 0;//除5余3的和
	int ans4_count = 0;//除5余3的个数
	double ans4;//除5余3的平均数
	int ans5 = 0;//除5余4中最大数
	int n, tmp;
	int yushu;
	cin >> n;
	for (int i = 0; i < n; i++) {
		cin >> tmp;
		//判断每一种数字
		yushu = tmp % 5;
		switch (yushu)
		{
		case 0:
			if (tmp % 2 == 0) {
				ans1 += tmp;
			}
			break;
		case 1:
			ans2_count++;
			if (ans2_flag) {
				//负
				ans2 -= tmp;
				ans2_flag = 0;
			}
			else {
				//正
				ans2 += tmp;
				ans2_flag = 1;
			}
			break;
		case 2:
			ans3++;
			break;
		case 3:
			ans4_count++;
			ans4_sum += tmp;
			break;
		case 4:
			if (tmp > ans5) {
				ans5 = tmp;
			}
			break;
		}
	}
	//单独计算ans4
	ans4 = (double)ans4_sum / ans4_count;
	if (ans1) {
		cout << ans1 << " ";
	}
	else {
		cout << "N ";
	}
	if (ans2_count) {
		cout << ans2 << " ";
	}
	else {
		cout << "N ";
	}
	if (ans3) {
		cout << ans3 << " ";
	}
	else {
		cout << "N ";
	}
	if (ans4_count) {
		printf("%.1f ", ans4);
	}
	else {
		cout << "N ";
	}
	if (ans5) {
		cout << ans5;
	}
	else {
		cout << "N";
	}
	
}

原文地址:https://www.cnblogs.com/ericling/p/12332036.html