每条线代表一个随机学生的成绩 每列代表一个随机科目的成绩 找出每个学生获得的最高成绩 预期的输出是:
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);
}
关于c# - 如何找到二维数组(矩阵)c#中每一行的最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65020843/