C#技术问题:如何从多个学生平均分中找出最高平均分
嗨,我来帮你搞定这个问题!你现在的代码里没有保存每个学生的平均分和对应姓名,所以没法找出最高分的学生。咱们可以通过几个小改动轻松实现这个功能,具体步骤如下:
第一步:定义存储学生信息的类
首先,咱们创建一个简单的类来保存每个学生的姓名和平均分,这样数据管理起来更清晰:
public class StudentScore { public string Name { get; set; } public double AverageScore { get; set; } }
第二步:在Main方法中添加列表存储所有学生信息
在Main方法开头,声明一个列表来记录每个学生的姓名和平均分,然后在处理每个学生的循环里,把计算好的信息存入列表:
static void Main(string[] args) { // 新增:用来存储所有学生的姓名和平均分 List<StudentScore> studentScores = new List<StudentScore>(); int total = 0; int gt50Count = 0; Console.WriteLine("How many students do you want to enter?"); int studentCount = int.Parse(Console.ReadLine()); for (int i = 0; i < studentCount; i++) { Console.WriteLine($"\nEnter student {i+1}'s name:"); string studentName = Console.ReadLine(); total = 0; gt50Count = 0; for (int j = 0; j < 5; j++) { Console.WriteLine($"Enter score {j+1} for {studentName}:"); int score = int.Parse(Console.ReadLine()); total += score; if (score > 50) { gt50Count++; } } double average = (double)total / 5; // 输出当前学生的原有信息 Console.WriteLine($"\n{studentName}'s total score: {total}"); Console.WriteLine($"{studentName}'s average score: {average:F2}"); Console.WriteLine($"{studentName}'s number of subjects above 50: {gt50Count}"); // 新增:把当前学生的姓名和平均分存入列表 studentScores.Add(new StudentScore { Name = studentName, AverageScore = average }); } // 第三步:找出平均分最高的学生 if (studentScores.Count > 0) { // 用LINQ快速找出最高分和对应的学生(支持并列情况) double highestAverage = studentScores.Max(s => s.AverageScore); var topStudents = studentScores.Where(s => s.AverageScore == highestAverage).ToList(); Console.WriteLine("\n=== 平均分最高的学生 ==="); foreach (var student in topStudents) { Console.WriteLine($"姓名:{student.Name},平均分:{student.AverageScore:F2}"); } } else { Console.WriteLine("没有输入任何学生信息哦。"); } }
可选:不用LINQ的手动遍历版本
如果你不想用LINQ,也可以手动遍历列表来找到最高分,逻辑更直观:
// 手动遍历找最高分的替代代码 if (studentScores.Count > 0) { double highestAvg = double.MinValue; List<string> topStudentNames = new List<string>(); foreach (var student in studentScores) { if (student.AverageScore > highestAvg) { // 找到更高分,更新最高分并清空之前的名单 highestAvg = student.AverageScore; topStudentNames.Clear(); topStudentNames.Add(student.Name); } else if (student.AverageScore == highestAvg) { // 遇到同分学生,添加到名单中 topStudentNames.Add(student.Name); } } Console.WriteLine("\n=== 平均分最高的学生 ==="); foreach (var name in topStudentNames) { Console.WriteLine($"姓名:{name},平均分:{highestAvg:F2}"); } }
这样修改后,不仅能找出平均分最高的学生,还能处理多个学生并列最高分的情况,完全满足你的需求!
内容的提问来源于stack exchange,提问作者A K
相关产品推荐
相关产品推荐

