C# 宿舍篮球队员选拔:找出每个宿舍最高的同学

问题描述:

用C#编写学校选拔篮球队员,每间宿舍最多有4个人。现给出宿舍列表,请找出每个宿舍最高的同学。

输入格式:

首先输入一个整型数n (1<=n<=1000000),表示n位同学。 紧跟着n行输入,每一行格式为:宿舍号,name,height,weight。 宿舍号的区间为[000000,999999], name 由字母组成,长度小于16,height,weight为正整数。

输出格式:

按宿舍号从小到大排序,输出每间宿舍身高最高的同学信息(同宿舍相同身高的同学只输出用户先录入的学生的信息)。题目保证每间宿舍只有一位身高最高的同学。

解题思路:

  1. 定义一个字典,键为宿舍号,值为该宿舍的所有学生列表;
  2. 读入每个学生信息,将其添加到相应的宿舍列表中;
  3. 对每个宿舍的学生列表按照身高进行排序,取出最高的学生;
  4. 输出每个宿舍的最高学生信息。

注意事项:

  1. 学生信息的输入格式,需要使用字符串类型读入,再进行分割,例如'001234 tom 170 60',可以使用String.Split()方法进行分割;
  2. 宿舍号需要补齐至6位,可以使用String.PadLeft()方法进行补齐。

参考代码:

using System;
using System.Collections.Generic;
using System.Linq;

public class Student
{
    public string Sid { get; set; }
    public string Name { get; set; }
    public int Height { get; set; }
    public int Weight { get; set; }

    public Student(string sid, string name, int height, int weight)
    {
        Sid = sid;
        Name = name;
        Height = height;
        Weight = weight;
    }

    public void Display()
    {
        Console.WriteLine($'宿舍号:{Sid}, 姓名:{Name}, 身高:{Height}, 体重:{Weight}');
    }
}

public class Program
{
    public static void Main(string[] args)
    {
        // 输入学生数量
        Console.WriteLine('请输入学生数量:');
        int n = Convert.ToInt32(Console.ReadLine());

        // 创建字典,存储宿舍号和学生列表
        Dictionary<string, List<Student>> dormStudents = new Dictionary<string, List<Student>>();

        // 读取学生信息
        for (int i = 0; i < n; i++)
        {
            Console.WriteLine('请输入学生信息(宿舍号 姓名 身高 体重):');
            string[] studentInfo = Console.ReadLine().Split(' ');

            // 补齐宿舍号到6位
            string sid = studentInfo[0].PadLeft(6, '0');

            // 创建学生对象
            Student student = new Student(sid, studentInfo[1], Convert.ToInt32(studentInfo[2]), Convert.ToInt32(studentInfo[3]));

            // 将学生添加到字典中
            if (dormStudents.ContainsKey(sid))
            {
                dormStudents[sid].Add(student);
            }
            else
            {
                dormStudents.Add(sid, new List<Student>() { student });
            }
        }

        // 遍历字典,输出每个宿舍最高的同学
        foreach (var dorm in dormStudents.OrderBy(x => x.Key))
        {
            // 对每个宿舍的学生列表进行排序
            List<Student> sortedStudents = dorm.Value.OrderByDescending(x => x.Height).ToList();

            // 输出最高的学生信息
            sortedStudents[0].Display();
        }
    }
}
C# 宿舍篮球队员选拔:找出每个宿舍最高的同学

原文地址: https://www.cveoy.top/t/topic/n488 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录