PAT training notes: Grade B Zhenti---Number Classification (20)

1. Title description

Title description

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

A1 = 能被5整除的数字中所有偶数的和;
A2 = 将被5除后余1的数字按给出顺序进行交错求和,即计算n1-n2+n3-n4...;
A3 = 被5除后余2的数字的个数;
A4 = 被5除后余3的数字的平均数,精确到小数点后1位;
A5 = 被5除后余4的数字中最大数字。

Enter description:

每个输入包含1个测试用例。每个测试用例先给出一个不超过1000的正整数N,随后给出N个不超过1000的待分类的正整数。数字间以空格分隔。

Output description:

对给定的N个正整数,按题目要求计算A1~A5并在一行中顺序输出。数字间以空格分隔,但行末不得有多余空格。
若其中某一类数字不存在,则在相应位置输出“N”。

Input example:

13 1 2 3 4 5 6 7 8 9 10 20 16 18

Output example:

30 11 2 9.7 9

2. My AC code

#include<stdio.h>
#include<math.h>

int main(){
	int n, a1, a2, a3, a5, a, i, j, c, d, e;
	float k, a4;
	scanf("%d", &n);
	a1 = a2 = a3 = a4 = a5 = d = 0;
	for( i = 1, j = 0, k = 0.0; i <= n; i++){
		scanf("%d", &a);
		switch (a % 5){
			case 0 : if(a % 2 == 0) a1 += a; break;
			case 1 : a2 += pow(-1, j) * a; j++; break;
			case 2 : a3++; break;
			case 3 : a4 += a; k++; break;
			case 4 : if( a > a5) a5 = a; d++;
		}
//		if(a%5 == 0 && a % 2 == 0)
//			a1 += a;
//		else if( a % 5 == 1){
//			a2 += pow(-1, j) * a;
//			j++;
//		}
//		else if( a % 5 == 2)
//			a3++;
//		else if( a % 5 == 3){
//			a4 += a;
//			k++;
//		}
//		else if( a % 5 == 4){
//			if( a > a5){
//				a5 = a;
//			}
//		}	
	} 
	
	if(a1) printf("%d ", a1);
	else printf("N ");
	if(j != 0) printf("%d ", a2);
	else printf("N ");
//	直接判断j即可,只要j大于零,那么就输出a2的值。 
	if(a3 != 0) printf("%d ", a3);
	else printf("N ");
	if(k) printf("%.1f ", a4/k);
	else printf("N ");
	if(d) printf("%d", a5);
	else printf("N");
}

Three, experience related

1. Problem analysis:

  • Test point 1: Data input and output;

  • Test point two: basic loop, judgment grammar;

Second, experience

  • There are some special cases to consider in this topic: when the interleaved sum result is 0, it does not mean that the second type of number does not exist, so I added a variable here to determine whether the calculation of the second type of number is performed, and if it is entered For the calculation of the second type of numbers, this value can be output directly at the end.
  • When calculating the interleaving series, I used the power: a^b, and then I found out that there was a problem with the output, and then I learned that this is an XOR operation in binary. If you want to achieve the power operation I need, you need to use the mathematical function pow(, );

  • In addition, I started to use the if branch statement, which is a bit bloated, and it looks more concise and comfortable after changing to the switch statement;

  • I found that the readability of my own code is still poor, a, i, j, c, d, e; this part of the data cannot be clear at a glance, it should be like some students wrote, count1, count2...... This corresponds to the calculation number Auxiliary variables like numbers increase the readability of the code.

 

 

 

 

 

 

 

 

 

Guess you like

Origin blog.csdn.net/qq_41914687/article/details/103942118