思路:
用的方法不是很好,创建五个全局变量,用来表示对应的五个数字存不存在,如果存在,那就给设置为1,用来控制我们输出的是N 还是 具体数字。我这里为了思路清晰,就对应创建了五个函数,其实是可以直接写在一起的,就五个数,个数我们是知道的,按照顺序输出空格和数字就行了
需要掌握的要点:
1,静态全局变量
2,C++ 控制输出位数
3,何时使用引用传参
代码:
#include<stdio.h>
#include<iostream>
#include<vector>
#include<iomanip>
using namespace std;
int iflag1 = 0;
int iflag2 = 0;
int iflag3 = 0;
int iflag4 = 0;
int iflag5 = 0;
int evenNumber(vector<int>& ivec, vector<int>::iterator iter, vector<int>::iterator iter_end) {
int sum = 0;
for (; iter != iter_end; iter++) {
if (*iter % 10 == 0) {
iflag1 = 1;
sum += *iter;
}
}
return sum;
}
int remainOne(vector<int>& ivec, vector<int>::iterator iter, vector<int>::iterator iter_end) {
bool flag = true;
int sum = 0;
for (; iter != iter_end; iter++) {
if (*iter % 5 == 1) {
iflag2 = 1;
if (flag == true) {
sum += *iter;
flag = false;
}
else if (flag == false) {
sum += -*iter;
flag = true;
}
}
}
return sum;
}
int remainNumber(vector<int>& ivec,vector<int>::iterator iter,vector<int>::iterator iter_end) {
int sum = 0;
for (; iter != iter_end; iter++) {
if (*iter % 5 == 2) {
iflag3 = 1;
sum++;
}
}
return sum;
}
double averNum(vector<int>& ivec, vector<int>::iterator iter, vector<int>::iterator iter_end) {
double sum = 0;
int num=0;
for (; iter != iter_end; iter++) {
if (*iter % 5 == 3) {
iflag4 = 1;
sum += *iter;
num++;
}
}
return sum / num;
}
int MaxNum(vector<int>& ivec, vector<int>::iterator iter, vector<int>::iterator iter_end) {
int m = 0;
for (; iter != iter_end; iter++) {
if (*iter % 5 == 4) {
iflag5 = 1;
if (*iter > m) {
m = *iter;
}
}
}
return m;
}
int main() {
int N;
int K;
int A1, A2, A3, A5;
double A4;
cin >> N;
vector<int> ivec;
for (int i = 0; i < N; i++) {
cin >> K;
ivec.push_back(K);
}
vector<int>::iterator iter = ivec.begin();
vector<int>::iterator iter_end = ivec.end();
A1 = evenNumber(ivec, iter, iter_end);
if (iflag1 == 0) {
cout << "N";
}
else {
cout << A1;
}
A2 = remainOne(ivec, iter, iter_end);
if (iflag2 == 0) {
cout << " N";
}
else {
cout << " " << A2;
}
A3 = remainNumber(ivec, iter, iter_end);
if (iflag3 == 0) {
cout << " N";
}
else {
cout << " " << A3;
}
A4 = averNum(ivec, iter, iter_end);
if (iflag4 == 0) {
cout << " N";
}
else {
printf(" %.1f", A4);
}
A5 = MaxNum(ivec, iter, iter_end);
if (iflag5 == 0) {
cout << " N";
}
else {
cout << " " << A5;
}
}