如何在2d数组(矩阵)c#中找到每行的最高值

  • 本文关键字:最高值 2d 数组 矩阵 c# arrays
  • 更新时间 :
  • 英文 :


每一行代表随机眩晕的等级每一列代表一个随机科目的成绩找出每个学生的最高成绩预期输出为:

The student 0 has the highest grade =  10
The student 1 has the highest grade =  10
The student 2 has the highest grade =  10
The student 3 has the highest grade =  10
The student 4 has the highest grade =  10
The student 5 has the highest grade =  9

这是阵列:

double[,] grades;
grades = new double[6, 4];
grades[0, 0] = 8; grades[0, 1] = 10; grades[0, 2] = 9; grades[0, 3] = 7;
grades[1, 0] = 7; grades[1, 1] = 9; grades[1, 2] = 8; grades[1, 3] = 10;
grades[2, 0] = 6; grades[2, 1] = 6; grades[2, 2] = 7; grades[2, 3] = 10;
grades[3, 0] = 6; grades[3, 1] = 5; grades[3, 2] = 10; grades[3, 3] = 7;
grades[4, 0] = 10; grades[4, 1] = 4; grades[4, 2] = 9; grades[4, 3] = 8;
grades[5, 0] = 9; grades[5, 1] = 7; grades[5, 2] = 5; grades[5, 3] = 9;  

这是我的代码:

double maxGrade;   
maxGrade = grades[0, 0];
for(int student = 0; student < note.GetLength(0); student++)
{
for(int subject = 0; subject < note.GetLength(1); subject++)
{
if (grades[student, subject] > maxGrade)
maxGrade = grades[student, subject];          
}
Console.WriteLine("The student " + student + " has the highest grade =  " + maxGrade);
}
My output is :
The student 0 has the highest grade =  10
The student 1 has the highest grade =  10
The student 2 has the highest grade =  10
The student 3 has the highest grade =  10
The student 4 has the highest grade =  10
The student 5 has the highest grade =  10

您在学生之间保留maxGrade,这会导致错误的结果。你需要为每个学生重新初始化:

for (int student = 0; student < note.GetLength(0); student++)
{
double maxGrade = grades[student, 0];
// Note you can start the iteration at 1, since you already grabbed index 0
for (int subject = 1; subject < note.GetLength(1); subject++)
{
if (grades[student, subject] > maxGrade) {
maxGrade = grades[student, subject];
}
}
Console.WriteLine("The student " + student + " has the highest grade =  " + maxGrade);
}

最新更新