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

using System;
using System.Collections.Generic;

namespace exci6_4
{
    class Program
    {
        static void Main(string[] args)
        {
            List<Student> students = new List<Student>();
            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 方法进行比较和排序。最后按照排序后的顺序输出每个学生的总分、英语成绩和数学成绩。


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

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