PAT basic 1012 数字分类 (20分) C++

PAT basic 1012 数字分类 (20分) C++

一、题目描述

给定一系列正整数,请按要求对数字进行分类,并输出以下 5 个数字:

A​1= 能被 5 整除的数字中所有偶数的和;
A​2= 将被 5 除后余 1 的数字按给出顺序进行交错求和,即计算 n​1−n​2
+n​3−n​4⋯;
A​3= 被 5 除后余 2 的数字的个数;
A4 = 被 5 除后余 3 的数字的平均数,精确到小数点后 1 位;
A​5= 被 5 除后余 4 的数字中最大数字。
输入格式:
每个输入包含 1 个测试用例。每个测试用例先给出一个不超过 1000 的正整数 N,随后给出 N 个不超过 1000 的待分类的正整数。数字间以空格分隔。

输出格式:
对给定的 N 个正整数,按题目要求计算 A​1~A​5
​​ 并在一行中顺序输出。数字间以空格分隔,但行末不得有多余空格。

若其中某一类数字不存在,则在相应位置输出 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<stdlib.h>
#include<math.h>
#include<iostream>
using namespace std;

int main()
{
	int n, temp, left;
	int a[5] = { 0 };
	int c[5] = { 0 };
	int a2flag = 1, a3count = 0;
	cin >> n;
	for (int i = 0; i<n; i++)
	{
		cin >> temp;
		left = temp % 5;
		switch (left)
		{
		case 0:
		{
			if (temp % 2 == 0)
			{
				a[0] += temp; c[0]++;
			}
			break;
		}
		case 1:
		{
			if (a2flag == 1)
			{
				a[1] += temp; a2flag = 0; c[1]++;
			}
			else
			{
				a[1] -= temp; a2flag = 1; c[1]++;
			}
			break;
		}
		case 2:
		{
			a[2]++;
			c[2]++;
			break;
		}
		case 3:
		{
			a[3] += temp;
			a3count++;
			c[3]++;
			break;
		}
		case 4:
		{
			c[4]++;
			if (temp > a[4])
				a[4] = temp;
			break;
		}
		default:break;
		}


	}
	float a3ave = 1.0*a[3] / a3count;
	if (c[0] == 0)
	{
		cout << "N";
	}
	else cout << a[0];
	for (int i = 1; i < 5; i++)
	{
		if (c[i] == 0)
		{
			cout << " N";
			continue;
		}
		else if (i != 3)
				cout << " " << a[i];
			else
				printf(" %.1f", a3ave);
	}

	system("pause");
	return 0;
}

三、运行结果

在这里插入图片描述

四、题目合集

点这里~

发布了42 篇原创文章 · 获赞 0 · 访问量 777

猜你喜欢

转载自blog.csdn.net/qq_44352065/article/details/103774565