Wednesday, July 19, 2017

PAT (Basic Level) Practise (中文) 1012

1012. 数字分类 (20)

时间限制
100 ms
内存限制
65536 kB
代码长度限制
8000 B
判题程序
Standard
作者
CHEN, Yue
给定一系列正整数,请按要求对数字进行分类,并输出以下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
  • 
    
  • //C++ Program
    #include <iostream>
    #include <cstring>
    #include <iomanip>
    using namespace std;
    
    int main(void) {
    
     int N, num, sign = -1, count = 0;
     float A[5] = { 0, 0, 0, 0, 0};//利用数组比较方便,下标与题目略有不同
     bool exist[5];//检测各类数字是否存在
     memset(exist, false, 5);//初始化
     cin >> N;
    
     for (int i = 0; i < N; ++i) {
      cin >> num;
      switch (num % 5) {
      case 0:
       if (num % 2 == 0) {
        if (!exist[0]) {
         exist[0] = true;
        }
        A[0] += num;
       }
       break;
      case 1:
       if (!exist[1]) {
        exist[1] = true;
       }
       sign *= -1;
       A[1] += (sign*num);
       break;
      case 2:
       if (!exist[2]) {
        exist[2] = true;
       }
       ++A[2];
       break;
      case 3:
       if (!exist[3]) {
        exist[3] = true;
       }
       ++count;
       A[3] += num;
       break;
      case 4:
       if (!exist[4]) {
        exist[4] = true;
       }
       if (num > A[4]) {
        A[4] = num;
       }
      }
     }
    
     A[3] /= count;
    
     for (int i = 0; i < 5; ++i) {
      if (i > 0) {
       cout << " ";
      }
      if (exist[i]) {
       if (i == 3) {
        cout << fixed<<setprecision(1);//精确到小数点后1位
       }
       else {
        cout << fixed << setprecision(0);
       }
       cout << A[i];
      }
      else {
       cout << "N";
      }
     }
    
     cout << endl;
    
     return 0;
    }
  • No comments:

    Post a Comment