以下为C#语言的代码实现:

using System; using System.Collections.Generic;

namespace exci6_4 { class Program { static void Main(string[] args) { List students = new List(); Console.Write("请输入学生数:"); int n = int.Parse(Console.ReadLine()); for (int i = 0; i < n; i++) { Console.Write("请输入第{0}个学生的英语和数学成绩(以空格分隔):", i + 1); string[] scores = Console.ReadLine().Split(' '); students.Add(new Student(int.Parse(scores[0]), int.Parse(scores[1]))); } students.Sort(); Console.WriteLine("排序后的结果为:"); foreach (Student student in students) { Console.WriteLine("总分为{0},英语成绩为{1},数学成绩为{2}", student.TotalScore, student.EnglishScore, student.MathScore); } } }

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方法进行比较和排序。最后按照排序后的顺序输出每个学生的总分、英语成绩和数学成绩

设计控制台应用程序项目exci6-4输入若干个学生的英语和数学成绩求出总分并按总分从高到低排序最出输出排序后的结果。要求比较采用继承 IComparable 接口的方式实现。

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

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