打印所有学生的成绩分布图,用星号来判断每次出现一个成绩

Print a grade Distribution chart of all students using stars to determine each time a grade appears

如标题所述。我现在完成了程序的大部分代码,这是最后一部分。老实说,此时我只是不明白如何执行此操作。我知道我应该使用类似于等级字母实现方式的实现方式,但是我如何实现它,以便对于等级范围内的每个等级,分布图将在相关等级范围内添加一个星号。

基本上分布图应该是这样的:

总体成绩分布:

0-9:

10-19:

20-29:

30-39:

40-49:

50-59:

60-69:***

70-79:******

80-89:***********

90-99: *******

100: ***

认为通过 link 提供所有代码可能会更好,所以现在开始:

This is my code on dotnetfiddle

我正试图解决这个问题。我被告知以 10 为单位从 0 循环到 100,然后嵌套循环从 0 循环到星星的数量。 N等于学生数量,5与每个学生的成绩数量有关:

for (int i = 0; i <= 100; i += 10)
{
    Console.WriteLine(i + " - " + (i + 10));
    for (int j = 0; j < (n*5); j++)
    {
        // add stars here
    }
}

查看您在 .net 上的代码 fiddle 首先,您需要实施一些方法来从学生那里取回成绩,在我的示例中,我使用了 GetGrades 方法。其次,我确信有比这更好或更清晰的方法 (linq),但至少它有效:)

        // Array where each value represents number of grades within range
        // distribution[0]: 0 - 9
        // distribution[1]: 10 - 19
        // distribution[2]: 20 - 29
        // distribution[3]: 30 - 39
        // distribution[4]: 40 - 49
        // distribution[5]: 50 - 59
        // distribution[6]: 60 - 69
        // distribution[7]: 70 - 79
        // distribution[8]: 80 - 89
        // distribution[9]: 90 - 99
        // distribution[10]: 100
        var distribution = new int[11]; 
        // Fill the array with distribtions for all students 
        // *Don't forget to implement GetGradse method for student 
        foreach (var s in students)
        foreach (var g in s.GetGrades())
        {
            // skip the grade thats less than 0 or greater than 100 (invalid grade)
            // in every other case increment distribution at g / 10 index
            if (g < 0 || g > 100) continue;
            else distribution[(int)g / 10]++;
        }
        // Now we can print out the grades distribution
        for (var i = 0; i < distribution.Length - 1; i++)
            Console.WriteLine($"{i * 10}-{i * 10 + 9}: {new String('*', distribution[i])}");
        Console.WriteLine($"100: {new String('*', distribution[10])}");

编辑(另一种方法,打印部分保持不变):您还可以在学生数组旁边声明分布数组,并在相同的位置填充它你给学生打分,如果你这样做,你就不需要再次循环遍历所有学生和成绩:

            ...
            Student[] students = new Student[n];
            var distribution = new int[11];
            ...
            for (int j = 0; j < 5; j++)
            {
                Console.WriteLine($"Enter grade {j + 1} for student {i + 1}: ");
                double grade = double.Parse(Console.ReadLine());
                students[i].addGrade(grade);
                // assuming grade value won't be greater than 100 or less than 0
                distributions[(int)grade / 10]++;
            }
            ...
            ...