C# - 检查值在数组中出现的次数并查找索引

时间:2016-06-24 11:08:54

标签: c# arrays indexof

我必须编写一个简单的程序,您必须输入学生姓名及其平均成绩,然后打印出最高的平均成绩及其所属的成绩。这里有几个主题,介绍如何在数组中查找值。我正在努力的是如果有超过1名学生的最高平均成绩,该怎么办。

这是我到目前为止所拥有的:

        Console.WriteLine("Enter the overall count of students.");


        int stuCount = Convert.ToInt32(Console.ReadLine());
        string[] name = new string[stuCount];
        double[] avg = new double[stuCount];

        for (int i = 0; i < stuCount; i++)
        {
            Console.WriteLine("Enter the name of student # {0}.", i + 1);
            name[i] = Console.ReadLine();
            Console.WriteLine("Enter the average grade of {0}.", name[i]);
            avg[i] = Convert.ToDouble(Console.ReadLine());
        }

        // Finding the max average
        double maxAvg = avg[0];
        for (int i = 1; i < stuCount; i++)
        {
            if (avg[i] > maxAvg)
            {
                maxAvg = avg[i];
            }
        }

        // Displaying the max average
        Console.WriteLine("The highest average grade is {0}.", maxAvg);

那么,我可以使用Array.IndexOf()方法查找多个索引吗?

谢谢。

3 个答案:

答案 0 :(得分:2)

考虑使用一个类来表示等级;

class Grade {
    public String Name {get;set;}
    public double Average {get;set;}
}

然后你的代码就更像了;

Console.WriteLine("Enter the overall count of students.");

        int stuCount = Convert.ToInt32(Console.ReadLine());         

        List<Grade> allGrades = new List<Grade>();

        for (int i = 0; i < stuCount; i++)
        {
            Console.WriteLine("Enter the name of student # {0}.", i + 1);
            var name = Console.ReadLine();
            Console.WriteLine("Enter the average grade of {0}.", name[i]);
            var avg = Convert.ToDouble(Console.ReadLine());
            Grade current = new Grade(){
                Name = name, 
                Average = avg
            };
            allGrades.Add(current);
        }

        // Finding the max average
        double maxAvg = allGrades.Max(g => g.Average);
        var highestGrades = allGrades.Where(g => g.Average == maxAvg);

        Console.WriteLine("The following Student(s) have the highest average grade:");
        foreach(var grade in highestGrades){
                // Displaying the max average
                Console.WriteLine("Student: {0}. Grade: {1}.", grade.Name, grade.Average);
        }
}

答案 1 :(得分:0)

另一种方法是创建一个包含两个属性(nameaverage grade)的类,然后生成List并将其填入for周期。下一步是order by descending列表到average grade并选择前N个元素等于。之后,您只需使用ForEach

打印结果即可

答案 2 :(得分:-1)

在您发现最高平均值之后,再次通过averages数组循环查看哪些是最大值并使用索引打印出螺柱。

Console.WriteLine("The highest average grade is {0}.", maxAvg);

Console.WriteLine("The students with this average grade are");
        for (int i = 0; i < stuCount; i++)
        {
            if (avg[i] == maxAvg)
            {
                 Console.WriteLine(name[i]);
            }
        }