C# 宿舍选拔最高同学:字典存储与比较身高
using System; using System.Collections.Generic;
class Student { public string sid; // 宿舍号 public string name; // 姓名 public int height; // 身高 public int weight; // 体重
public Student(string 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);
}
}
class Program { static void Main(string[] args) { int n = int.Parse(Console.ReadLine()); // 读入人数 Dictionary<string, Student> dict = new Dictionary<string, Student>(); // 用字典存储每个宿舍的最高同学 for (int i = 0; i < n; i++) { string[] s = Console.ReadLine().Split(); // 读入一行数据 string sid = s[0]; string name = s[1]; int height = int.Parse(s[2]); int weight = int.Parse(s[3]); if (!dict.ContainsKey(sid)) // 如果该宿舍还没有对应的学生信息 { dict[sid] = new Student(sid, name, height, weight); // 直接添加 } else // 该宿舍已有对应的学生信息,需要比较身高 { if (height > dict[sid].height) // 如果该学生身高更高 { dict[sid] = new Student(sid, name, height, weight); // 更新为该学生信息 } } } foreach (var item in dict) { item.Value.Display(); // 输出每个宿舍的最高同学信息 } } }
原文地址: https://www.cveoy.top/t/topic/n49x 著作权归作者所有。请勿转载和采集!