C# 编写学校选拔篮球队员程序:找出每个宿舍最高的同学
C# 编写学校选拔篮球队员程序:找出每个宿舍最高的同学
问题描述:
用 C# 编写学校选拔篮球队员程序,每间宿舍最多有 4 个人。现给出宿舍列表,请找出每个宿舍最高的同学。定义一个学生类 Student, 包含数据成员宿舍号 sid, 姓名 name,身高 height(整数),体重 weight(整数),公有构造函数用于初始化数据成员,公有方法 Display() 用于输出。
输入格式:
首先输入一个整型数 n (1<=n<=1000000),表示 n 位同学。 紧跟着 n 行输入, 每一行格式为:宿舍号,name, height, weight。 宿舍号的区间为[000000,999999], name 由字母组成,长度小于 16,height,weight 为正整数。
输出格式:
按宿舍号从小到大排序,输出每间宿舍身高最高的同学信息(同宿舍相同身高的同学只输出用户先录入的学生的信息)。题目保证每间宿舍只有一位身高最高的同学。
解题思路:
首先,需要将输入的 n 个学生按照宿舍号从小到大排序,可以使用 List
C# 代码:
using System;
using System.Collections.Generic;
using System.Linq;
public class Student
{
public int sid { get; set; } // 宿舍号
public string name { get; set; } // 姓名
public int height { get; set; } // 身高
public int weight { get; set; } // 体重
public Student(int sid, string name, int height, int weight)
{
this.sid = sid;
this.name = name;
this.height = height;
this.weight = weight;
}
public void Display()
{
Console.WriteLine($'宿舍号: {sid}, 姓名: {name}, 身高: {height}, 体重: {weight}');
}
}
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine('请输入学生人数:');
int n = int.Parse(Console.ReadLine());
List<Student> students = new List<Student>();
Console.WriteLine('请输入学生信息(宿舍号 姓名 身高 体重):');
for (int i = 0; i < n; i++)
{
string[] input = Console.ReadLine().Split(' ');
students.Add(new Student(int.Parse(input[0]), input[1], int.Parse(input[2]), int.Parse(input[3])));
}
// 按宿舍号排序
students = students.OrderBy(s => s.sid).ToList();
// 找出每个宿舍最高的同学
Dictionary<int, Student> highestStudents = new Dictionary<int, Student>();
foreach (Student student in students)
{
if (!highestStudents.ContainsKey(student.sid) || student.height > highestStudents[student.sid].height)
{
highestStudents[student.sid] = student;
}
}
// 输出结果
foreach (KeyValuePair<int, Student> entry in highestStudents.OrderBy(e => e.Key))
{
entry.Value.Display();
}
}
}
程序说明:
- 程序首先定义了一个名为 Student 的类,用于存储每个学生的信息,包括宿舍号、姓名、身高和体重。
- 程序使用 List
存储所有学生的信息,并使用 LINQ 的 OrderBy 方法对学生列表按照宿舍号进行排序。 - 程序使用 Dictionary<int, Student> 存储每个宿舍身高最高的同学信息,键值对中的键是宿舍号,值是身高最高的同学对象。
- 程序遍历排序后的学生列表,对于每个学生,判断其宿舍号是否已经在 Dictionary 中存在,如果不存在,则将该学生添加到 Dictionary 中;如果存在,则判断该学生的身高是否大于 Dictionary 中已存储的同学的身高,如果大于,则用该学生替换 Dictionary 中的同学。
- 程序最后按宿舍号从小到大输出每个宿舍身高最高的同学信息。
原文地址: https://www.cveoy.top/t/topic/n48Y 著作权归作者所有。请勿转载和采集!