1012 数字分类 (20 分)- PAT乙级真题

版权声明:您的支持是我不懈努力的动力^_^, https://blog.csdn.net/weixin_43905586/article/details/87928681

题滴链接https://pintia.cn/problem-sets/994805260223102976/problems/994805311146147840

1012 数字分类 (20 分)

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

  • A​1​​ = 能被 5 整除的数字中所有偶数的和;
  • A​2​​ = 将被 5 除后余 1 的数字按给出顺序进行交错求和,即计算 n​1​​−n​2​​+n​3​​−n​4​​⋯;
  • A​3​​ = 被 5 除后余 2 的数字的个数;
  • A​4​​ = 被 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

鄙人拙见:

  1.  按顺序输出
  2. A1 A2 A3 A4 A5

C++参考代码1.0:  

#include <bits/stdc++.h>
using namespace std;

void A1(int * num, int n)
{
	int sum = 0;
	int count = 0;
	for(int i = 0; i < n; i++)
	{
		if(num[i] % 5 == 0 && num[i] % 2 == 0)
		{
			sum = sum + num[i];
			count = count + 1;
		}	
	}
	if(count > 0)
	{
		printf("%d ",sum);
	}
	else
	{
		printf("N ");
	}

}

int jishu(int * a, int k)
{
	int a1[k];
	int t = 0;
	for(int i = 0; i < k; i++)
	{
		if(i % 2 == 0)
		{
			a1[t] = a[i];
			t = t + 1;
		}	
	}
	int sum = 0;
	for(int i = 0; i < t; i++)
	{
		sum = sum + a1[i];
	}
	return sum;
}

int oushu(int * a, int k)
{
	int a1[k];
	int t = 0;
	for(int i = 0; i < k; i++)
	{
		if(i % 2 == 1)
		{
			a1[t] = a[i];
			t = t + 1;
		}	
	}
	int sum = 0;
	for(int i = 0; i < t; i++)
	{
		sum = sum + a1[i];
	}
	return sum;
}

void A2(int * num, int n)
{
	int sum = 0;
	int a[n];
	int k = 0;
	for(int i = 0; i < n; i++)
	{
		if(num[i] % 5 == 1)
		{
			a[k] = num[i];
			k = k + 1;
		}	
	}

	int a1,a2;
	a1 = jishu(a,k);
	a2 = oushu(a,k);
	
	int cha;
	cha = a1 - a2;
	
	if(k > 0)
	{
		printf("%d ",cha);
	}
	else
	{
		printf("N ");
	}

}

void A3(int * num, int n)
{
	int count = 0;
	for(int i = 0; i < n; i++)
	{
		if(num[i] % 5 ==  2)
		{
			count = count + 1;
		}	
	}
	if(count > 0)
	{
		printf("%d ",count);
	}
	else
	{
		printf("N ");
	}
}

void A4(int * num, int n)
{
	int sum = 0;
    int count = 0;
	for(int i = 0; i < n; i++)
	{
		if(num[i] % 5 == 3)
		{
			sum = sum + num[i];	
			count = count + 1;
		}	
	}	
	double jun;
	jun = (double)sum / count;
	
	if(count > 0)
	{
		printf("%.1lf ",jun);
	}
	else
	{
		printf("N ");
	}
	
}

void A5(int * num, int n)
{
	int max = -1;
	int count = 0;
	for(int i = 0; i < n; i++)
	{
		if(num[i] % 5 == 4 && num[i] > max)
		{
			max = num[i];
			count = count + 1;	
		}	
	}
	if(count > 0)
	{
		printf("%d", max);
	}
	else
	{
		printf("N");
	}
}


int main() 
{
	int n;
	scanf("%d",&n);
	int num[n];
	for(int i = 0; i < n; i++)
	{
		scanf("%d",&num[i]);
	}
	A1(num,n);
	A2(num,n);
	A3(num,n);
	A4(num,n);
	A5(num,n);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_43905586/article/details/87928681