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

标签 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);
}

关于c# - 如何找到二维数组(矩阵)c#中每一行的最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65020843/

相关文章:

C# WPF ListView动态个性化每一行的字体大小

Visual Studio 2015 CTP 6 中的 C# 交互窗口

c# - db4o 查询 : find all objects with ID = {anything in array}

c# - 在 C# 中嵌入 IronPython 时如何处理值类型?

c# - C# 如何获取从开始日期到结束日期耗时

javascript - 如何使用jquery排除数组中的空值和键?

java - 两个不同的变量指向同一内存位置

javascript - 如何使用 ng-Repeat 来对数组对象进行 Angular 平移?

python - 当尺寸不匹配时,将第一个添加到 python 列表中

php - Array_filter 从数组中取消设置值