C# 多态实现学生和教师信息管理系统
using System;
namespace ConsoleApp1
{
class Person
{
protected int no; // 编号
public virtual void display() // 输出相关信息
{
}
}
class Student : Person
{
private int[] scores = new int[5]; // 5 门课程的成绩
public override void display()
{
int count = 0; // 已考科目数
int sum = 0; // 已考科目的总成绩
int absent = 0; // 缺考科目数
for (int i = 0; i < scores.Length; i++)
{
if (scores[i] != -1) // 已考
{
count++;
sum += scores[i];
}
else // 缺考
{
absent++;
}
}
Console.WriteLine("{0} {1} {2}", no, absent, count == 0 ? "N/A" : Math.Round((double)sum / count).ToString());
}
public Student(int no, int[] scores)
{
this.no = no;
this.scores = scores;
}
}
class Teacher : Person
{
private int[] papers = new int[3]; // 近 3 年发表的论文数量
public override void display()
{
int sum = 0;
for (int i = 0; i < papers.Length; i++)
{
sum += papers[i];
}
Console.WriteLine("{0} {1}", no, sum);
}
public Teacher(int no, int[] papers)
{
this.no = no;
this.papers = papers;
}
}
class Program
{
static void Main(string[] args)
{
Person[] persons = new Person[10]; // 存放学生或教师对象的数组
int index = 0; // 数组下标
while (true)
{
string input = Console.ReadLine();
if (input == "0")
{
break;
}
string[] inputs = input.Split();
int type = int.Parse(inputs[0]);
int no = int.Parse(inputs[1]);
if (type == 1) // 学生
{
int[] scores = new int[5];
for (int i = 0; i < scores.Length; i++)
{
scores[i] = int.Parse(inputs[i + 2]);
}
persons[index++] = new Student(no, scores);
}
else // 教师
{
int[] papers = new int[3];
for (int i = 0; i < papers.Length; i++)
{
papers[i] = int.Parse(inputs[i + 2]);
}
persons[index++] = new Teacher(no, papers);
}
}
for (int i = 0; i < index; i++)
{
persons[i].display();
}
}
}
}
代码说明:
- Person 基类: 定义了 Person 基类,包含编号 (no) 属性和一个虚拟方法 display(),用于输出基本信息。
- Student 类: 继承 Person 类,包含 5 门课程成绩 (scores) 属性,并重写 display() 方法,计算并输出缺考科目数、已考科目平均分。
- Teacher 类: 继承 Person 类,包含 3 年发表论文数量 (papers) 属性,并重写 display() 方法,计算并输出 3 年论文总数。
- Program 类: 主函数,定义了一个 Person 数组存放学生和教师对象,循环读取用户输入信息,根据类型创建 Student 或 Teacher 对象,并将对象存储到数组中。最后循环遍历数组调用每个对象的 display() 方法输出信息。
运行示例:
输入:
1 19 -1 -1 -1 -1 -1
1 125 78 66 -1 95 88
2 68 3 0 7
2 52 0 0 0
1 6999 32 95 100 88 74
0
输出:
19 5 N/A
125 1 82
68 10
52 0
6999 0 78
代码分析:
- 使用多态性,通过重写 display() 方法,使不同类型的对象以不同的方式输出信息。
- 使用循环读取输入数据,并根据类型创建相应的对象。
- 使用数组存储对象,便于统一管理和访问。
- 使用条件语句和循环语句实现不同的数据处理逻辑。
- 使用 Math.Round() 方法对平均分进行四舍五入取整。
- 使用字符串格式化输出信息,使输出格式更清晰规范。
总结:
这段代码通过 C# 的多态性、数组和输入输出等概念,实现了简单的学生和教师信息管理功能,体现了面向对象编程的优势和灵活运用。
原文地址: https://www.cveoy.top/t/topic/nTpP 著作权归作者所有。请勿转载和采集!