设计控制台应用程序项目exci6-4输入若干个学生的英语和数学成绩求出总分并按总分从高到低排序最出输出排序后的结果。要求比较采用继承 IComparable 接口的方式实现。
以下为C#语言的代码实现:
using System; using System.Collections.Generic;
namespace exci6_4
{
class Program
{
static void Main(string[] args)
{
List
class Student : IComparable<Student>
{
private int englishScore;
private int mathScore;
public int EnglishScore
{
get { return englishScore; }
set { englishScore = value; }
}
public int MathScore
{
get { return mathScore; }
set { mathScore = value; }
}
public int TotalScore
{
get { return englishScore + mathScore; }
}
public Student(int englishScore, int mathScore)
{
this.englishScore = englishScore;
this.mathScore = mathScore;
}
public int CompareTo(Student other)
{
return other.TotalScore - this.TotalScore;
}
}
}
程序首先输入学生数,然后循环输入每个学生的英语和数学成绩,将每个学生作为Student类的实例存入List中。List的Sort方法会自动调用Student类中的CompareTo方法进行比较和排序。最后按照排序后的顺序输出每个学生的总分、英语成绩和数学成绩
原文地址: https://www.cveoy.top/t/topic/cDJk 著作权归作者所有。请勿转载和采集!