我试图在2d数组中的行之间找到最大值和最小值——最小值代码似乎是正确的,但不起作用


#include <iostream>
using namespace std;
int main()
{
int total, average, maximum, mininum;
int a = 0;
int b = 0;
int c = 0;
int x = 0;
int y = 0;
int tab[5][5] = { { 111, 2, 30, 4, 500 }, { 10, 20, 30, 40, 50 }, 
{34, 54, 78, 9, 23,},
{ 65, 12, 98, 3, 78 }, { 34, 89, 23, 98, 45 } };
string name[5] = { "EMP1:EREN", "EMP2:ARMIN", "EMP3:MIKASA", "EMP4:LEVI", "EMP5:CONNIE" };
for (int c = 0; c < 5; c++) {
for (int a = 0; a < 5; a++) {
//cout<<total<<"n";
cout << tab[c][a] << "n";
3 total = total + tab[c][a];
b = tab[c][a];
for (tab[c][a] = 1; tab[c][a] >= 300; tab[c][a]++);
if (tab[c][a] >= x) {
x = tab[c][a];
}
for (tab[c][a] = 1; tab[c][a] < 5; tab[c][a]++);
if (tab[c][a] < b) {
y = tab[c][a];
}
}
average = total / 5;
cout << "I.D number " << name[c] << " nThe total amount of sale:" << total;
cout << "nThe average sales is:" << average;
cout << "nThe Maximum sales is:" << x;
cout << "nThe Minimum sales is:" << y << "n";
}
}

你的代码大多是c风格的,你的逻辑不是很清楚,我只是用accumulateminmax_element把它变成了现代的cpp风格,我们也可以把二维数组改成vectorstd::array,留给你。

使用的STL算法:

  • 累加求和
  • 用于将最小值和最大迭代器放在一起的minmax_element
#include <algorithm>
#include <iostream>
#include <numeric>
using namespace std;
int main() {
constexpr size_t kColomns = 5;
constexpr size_t kRows = 5;
int tab[kRows][kColomns] = {{111, 2, 30, 4, 500},
{10, 20, 30, 40, 50},
{34, 54, 78, 9, 23},
{65, 12, 98, 3, 78},
{34, 89, 23, 98, 45}};
string name[kRows] = {"EMP1:EREN", "EMP2:ARMIN", "EMP3:MIKASA", "EMP4:LEVI",
"EMP5:CONNIE"};
for (int c = 0; c < kRows; c++) {
auto total = std::accumulate(&tab[c][0], &tab[c][kColomns], 0);
auto average = total / kColomns;
auto [min_iter, max_iter] =
std::minmax_element(&tab[c][0], &tab[c][kColomns]);
cout << "I.D number " << name[c] << " nThe total amount of sale:" << total;
cout << "nThe average sales is:" << average;
cout << "nThe Maximum sales is:" << *min_iter;
cout << "nThe Minimum sales is:" << *max_iter << "n";
}
return 0;
}

输出:

I.D number EMP1:EREN
The total amount of sale:647
The average sales is:129
The Maximum sales is:2
The Minimum sales is:500
I.D number EMP2:ARMIN
The total amount of sale:150
The average sales is:30
The Maximum sales is:10
The Minimum sales is:50
I.D number EMP3:MIKASA
The total amount of sale:198
The average sales is:39
The Maximum sales is:9
The Minimum sales is:78
I.D number EMP4:LEVI
The total amount of sale:256
The average sales is:51
The Maximum sales is:3
The Minimum sales is:98
I.D number EMP5:CONNIE
The total amount of sale:289
The average sales is:57
The Maximum sales is:23
The Minimum sales is:98  

在线演示

相关内容

最新更新