给定一系列正整数,请按要求对数字进行分类,并输出以下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
#include<iostream>//这个程序用到了vector(不用事先考虑数组的大小) ,先将数字分成五类,然后对每类数字进行处理 #include<vector> #include<iomanip> using namespace std; int main(){ int n; while (cin >> n){ int *a = new int[n]; for (int i = 0; i<n; i++){ cin >> a[i]; } vector<vector<int> > A(5); for (int i = 0; i<n; i++){ if (a[i] % 5 == 0){ A[0].push_back(a[i]); } else if (a[i] % 5 == 1){ A[1].push_back(a[i]); } else if (a[i] % 5 == 2){ A[2].push_back(a[i]); } else if (a[i] % 5 == 3){ A[3].push_back(a[i]); } else if (a[i] % 5 == 4){ A[4].push_back(a[i]); } } int res_A0 = 0, res_A1 = 0, res_A2 = 0, res_A4 = 0; double res_A3 = 0.0; if (A[0].empty()){ cout << "N "; } else{ for (vector<int>::iterator iter = A[0].begin(); iter != A[0].end(); ++iter){ if ((*iter) % 2 == 0){ res_A0 += *iter; } } if (res_A0 == 0){ cout << "N "; } else{ cout << res_A0 << " "; } } if (A[1].empty()){ cout << "N "; } else{ int j = 0; for (vector<int>::iterator iter = A[1].begin(); iter != A[1].end(); ++iter, j++){ if (j % 2 == 0){ res_A1 += *iter; } else{ res_A1 -= *iter; } } cout << res_A1 << " "; } if (A[2].empty()){ cout << "N "; } else{ for (vector<int>::iterator iter = A[2].begin(); iter != A[2].end(); ++iter){ res_A2++; } cout << res_A2 << " "; } if (A[3].empty()){ cout << "N "; } else{ double k = 0.0; for (vector<int>::iterator iter = A[3].begin(); iter != A[3].end(); ++iter){ k++; res_A3 += *iter; } res_A3 = res_A3 / k; cout << fixed << setprecision(1) << res_A3 << " "; } if (A[4].empty()){ cout << "N" << endl; } else{ vector<int>::iterator iter = A[4].begin(); int max = *iter; for (; iter != A[4].end(); ++iter){ if (max<*iter){ max = *iter; } } cout << max << endl; } delete[] a; } system("pause"); return 0; }