gpt4 book ai didi

c++ - 数组函数似乎没有找到最高值

转载 作者:搜寻专家 更新时间:2023-10-31 01:32:11 24 4
gpt4 key购买 nike

我有一段代码应该从一组数组中返回最大的整数,每个数组包含三个整数。目前我的代码不工作。有人可以帮我找到我的错误吗?

下面是我的代码:

#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;
}

最佳答案

由于数组大小相同,因此您无需分别处理每个最大值。

highest 存储当前的最高值并被下一个最高值覆盖。

为什么不只是:

 int HighestScore(int St1[], int St2[], int St3[])
{
const int SIZE =3;
int count;
//make sure you have #include <limits.h> in the beginning
int highest = INT_MIN; //---lowest value of an integer in C;


for (count=0;count<SIZE;count++)
{
if(St1[count] > highest)
highest = St1[count];
if(St2[count] > highest)
highest = St2[count];
if(St3[count] > highest)
highest = St3[count];
}
cout << highest;
return highest;
}

对于最高的初始值,取整数中可能的最低值,这样可以保证覆盖。

整数的最小可能值也可以作为 limits.h 中的 INT_MIN。

关于c++ - 数组函数似乎没有找到最高值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43797583/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com