【发布时间】:2017-05-05 06:02:08
【问题描述】:
我有一段代码应该从一组包含三个整数的数组中返回最大的整数。目前我的代码不起作用。有人可以帮我找到我的错误吗?
下面是我的代码:
#include <iostream>
using namespace std;
void HighestScore(int[], int[], int[]);
int main() {
const int SIZE = 3;
int Stu1[SIZE] = {70, 80, 90},
Stu2[SIZE] = {71, 81, 91},
Stu3[SIZE] = {72, 82, 92},
Stu4[SIZE] = {73, 83, 93},
Stu5[SIZE] = {74, 84, 94};
HighestScore(Stu1,Stu2,Stu3);
return 0;
}
void HighestScore(int St1[], int St2[], int St3[])
{
const int SIZE =3;
int count;
int high1 = St1[0];
int high2 = St2[0];
int high3 = St3[0];
int highest =0;
for (count=1;count<SIZE;count++)
{
if(St1[count] > high1)
{high1 = St1[count];}
if(St2[count] >high2)
{high2 = St2[count];}
if(St3[count] >high3)
{high3 = St3[count];}
}
if(high1>high2)
{highest=high1;}
else if (high1>high3)
{highest=high1;}
else if (high2>high1)
{highest=high2;}
else if (high2>high3)
{highest=high2;}
else if (high3>high1)
{highest=high3;}
else if (high3>high2)
{highest=high3;}
else
{highest=-1;}
cout << highest;
return;
}
【问题讨论】:
-
high1、high2和high3是不必要的。您可以拥有SIZE的单个文件静态副本。考虑使用向量。与未知数量的一维数组相比,二维数组更容易扩展以添加学生(或二维向量)。 -
你的老师还没讲过二维数组吗?
-
你做的工作量太大,宁愿接受标准算法并了解
std::max_element。它以一种更安全、更简单、更符合 C++ 习惯的方式为您完成所有这些工作。