如何在C#中找到二维数组(矩阵)每行的最大值

3

每一行代表一个随机学生的成绩 每一列代表一个随机科目的成绩 找出每个学生获得的最高分数 期望输出为:

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

1
所以,人们不喜欢帮你做作业。写出你尝试过什么,哪些方法不起作用。尝试提出一个具体的问题。 - mikelegg
1个回答

0

你需要在每个学生之间重新初始化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);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接