C# 实验三

7-1 C# 3.1 Person派生类

分数 10

全屏浏览

切换布局

作者 陈卓

单位 青岛科技大学

给出下面的一个基类框架:
class Person
{ protected int no;//编号
public virtual void display()//输出相关信息
{ } }
以Person为基类,构建出Student、Teacher两个类。生成上述类并编写主函数,要求主函数中有一个基类Person的一维数组,用于存放学生或教师对象,数组长度为10。
主函数根据输入的信息,相应建立Student, Teacher类对象,对于Student给出期末5门课的成绩(为整数,缺考的科目填-1), 对于Teacher则给出近3年,每年发表的论文数量。

输入格式:

每个测试用例占一行,第一项为人员类型,1为Student,2为Teacher。接下来为编号(1-9999),接下来Student是5门课程成绩,Teacher是3年的论文数。最后一行为0,表示输入的结束。

输出格式:

要求输出编号,以及Student缺考的科目数和已考科目的平均分(四舍五入取整,已考科目数为0时,不输出平均分),Teacher的3年论文总数。

输入样例:

在这里给出一组输入。例如:

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
125 1 82
68 10
52 0
6999 0 78
using System;

class Person
{
    protected int no; // 编号

    public Person(int no)
    {
        this.no = no;
    }

    public virtual void display()
    {
        // 输出相关信息
    }
}

class Student : Person
{
    private int[] scores; // 5门课的成绩

    public Student(int no, int[] scores) : base(no)
    {
        this.scores = scores;
    }

    public override void display()
    {
        int missingExams = 0;
        int totalScore = 0;
        int examCount = 0;

        foreach (int score in scores)
        {
            if (score == -1)
            {
                missingExams++;
            }
            else
            {
                totalScore += score;
                examCount++;
            }
        }

        Console.Write(no + " " + missingExams);
        if (examCount > 0)
        {
            int averageScore = (int)Math.Round((double)totalScore / examCount);
            Console.Write(" " + averageScore);
        }
        Console.WriteLine();
    }
}

class Teacher : Person
{
    private int[] papers; // 3年发表的论文数量

    public Teacher(int no, int[] papers) : base(no)
    {
        this.papers = papers;
    }

    public override void display()
    {
        int totalPapers = 0;

        foreach (int paper in papers)
        {
            totalPapers += paper;
        }

        Console.WriteLine(no + " " + totalPapers);
    }
}

class Program
{
    static void Main(string[] args)
    {
        Person[] people = new Person[10];
        int count = 0;

        while (true)
        {
            string input = Console.ReadLine();
            if (input == "0") break;

            string[] parts = input.Split(' ');
            int type = int.Parse(parts[0]);
            int no = int.Parse(parts[1]);

            if (type == 1) // Student
            {
                int[] scores = new int[5];
                for (int i = 0; i < 5; i++)
                {
                    scores[i] = int.Parse(parts[2 + i]);
                }
                people[count++] = new Student(no, scores);
            }
            else if (type == 2) // Teacher
            {
                int[] papers = new int[3];
                for (int i = 0; i < 3; i++)
                {
                    papers[i] = int.Parse(parts[2 + i]);
                }
                people[count++] = new Teacher(no, papers);
            }
        }

        foreach (Person person in people)
        {
            if (person != null)
            {
                person.display();
            }
        }
    }
}


7-2 C# 3.2 Drink及其派送类

分数 20

全屏浏览

切换布局

作者 陈卓

单位 青岛科技大学

一个茶吧提供三类饮料:茶、咖啡和牛奶。其中本地茶要另加50%的服务费,其它茶要加20%的服务费;现磨咖啡要加100%的服务费,其它咖啡加20%的服务费;牛奶不加服务费。服务费精确到小数点后一位。定义饮料类Drink,它有三个受保护的字段分别记录饮料编号(整型),购买数量(整型),单价(最多1位小数);一个带三个参数的构造函数用来初始化字段;一个虚拟的成员方法用来计算并输出该编号的饮料总价格是多少(如果总价格为小数,则保留到小数点后一位,推荐使用Math.Round( )方法)。
以Drink为基类,构建出Tea、Coffee和Milk三个派生类。派生类Tea有一个私有的字段记录地区码(整型);有两个私有常量serviceCharge1和serviceCharge2,分别记录本地茶加收的服务费50%和其它茶加收的服务费20%。派生类Coffee有一个私有的字段记录加工类型(整型);有一个私有常量serviceCharge1和serviceCharge2,分别记录现磨咖啡加收的服务费100%和其它咖啡加收的服务费20%。(提示:应用重写虚拟实现多态)
主函数功能:定义一个Drink数组(长度10);根据用户输入的信息,相应建立Tea, Coffee或Milk类对象,计算并显示收费信息。用户输入的信息的每一行信息格式如下:
第一项为饮料的类型,茶为1,咖啡为2,牛奶为3。
第二项是申请的编号[100-999]。
第三项是数量。
第四项是单价。
第五项:对于茶叶来说,接下来输入一个地区代码,其中1代表本地;对于咖啡来说,接下来要输入一个加工代码,其中1代表现磨。对于牛奶来说没有第五项。
当用户输入的一行为0时,表示输入结束。

输入格式:

每个测试用例占一行,用户可输入多行测试用例。当用户输入的一行为0时,表示输入结束。

输出格式:

每一行输出对应用户的一行有效输入,输出饮料编号和收费(如果总价格为小数,则保留到小数点后一位,推荐使用Math.Round( )方法)。
如果某行测试记录饮料类型不为1,2,3,则该条输入对应的输出为”Drink type error.”
如果某行测试记录饮料类型对,但是饮料编号不在[100,999]之间,则输出”Drink ID error.”
如果某行测试记录饮料类型、编号对,购买数量小于0,则输出”Drink number error.”
如果某行测试记录饮料类型、编号、购买数量对,单价小于0,则输出”Drink price error.”
如果用户一行为0,则无输出结果。

输入样例:

在这里给出一组输入。例如:

1 106 3 33 1
1 103 2 20 2
3 109 1 15
2 107 2 15.8 1
2 232 3 21 29
0

输出样例:

在这里给出相应的输出。例如:

106 148.5
103 48
109 15
107 63.2
232 75.6
/*
    茶 : 本地茶 + 50% ; 其他茶 + 20%
    咖啡 : 现磨咖啡 + 100% ; 其他咖啡 + 20%
    牛奶 : 不加服务费
*/
using System;
using System.Collections.Generic;

class Drink
{
    protected int id;
    protected int quantity;
    protected double price;

    public Drink(int id, int quantity, double price)
    {
        this.id = id;
        this.quantity = quantity;
        this.price = price;
    }

    public virtual string CalculateAndDisplayTotalPrice()
    {
        double total = quantity * price;
        return $"{id} {Math.Round(total, 1)}";
    }
}

class Tea : Drink
{
    private int regionCode;
    private const double serviceCharge1 = 0.50; // 本地茶
    private const double serviceCharge2 = 0.20; // 其它茶

    public Tea(int id, int quantity, double price, int regionCode) : base(id, quantity, price)
    {
        this.regionCode = regionCode;
    }

    public override string CalculateAndDisplayTotalPrice()
    {
        double serviceCharge = regionCode == 1 ? serviceCharge1 : serviceCharge2;
        double total = quantity * price * (1 + serviceCharge);
        return $"{id} {Math.Round(total, 1)}";
    }
}

class Coffee : Drink
{
    private int processingType;
    private const double serviceCharge1 = 1.00; // 现磨咖啡
    private const double serviceCharge2 = 0.20; // 其它咖啡

    public Coffee(int id, int quantity, double price, int processingType) : base(id, quantity, price)
    {
        this.processingType = processingType;
    }

    public override string CalculateAndDisplayTotalPrice()
    {
        double serviceCharge = processingType == 1 ? serviceCharge1 : serviceCharge2;
        double total = quantity * price * (1 + serviceCharge);
        return $"{id} {Math.Round(total, 1)}";
    }
}

class Milk : Drink
{
    public Milk(int id, int quantity, double price) : base(id, quantity, price) { }

    public override string CalculateAndDisplayTotalPrice()
    {
        double total = quantity * price;
        return $"{id} {Math.Round(total, 1)}";
    }
}

class Program
{
    static void Main(string[] args)
    {
        Drink[] drinks = new Drink[10];
        int count = 0;
        List<string> res = new List<string>();
        while (true)
        {
            string input = Console.ReadLine();
            if (input == "0") break;

            string[] parts = input.Split(' ');
            int type = int.Parse(parts[0]);

            if (type < 1 || type > 3)
            {
                res.Add("Drink type error.");
                // Console.WriteLine();
                continue;
            }

            int id = int.Parse(parts[1]);
            if (id < 100 || id > 999)
            {
                res.Add("Drink ID error.");
                continue;
            }

            int quantity = int.Parse(parts[2]);
            if (quantity < 0)
            {
                res.Add("Drink number error.");
                continue;
            }

            double price = double.Parse(parts[3]);
            if (price < 0)
            {
                res.Add("Drink price error.");
                continue;
            }

            switch (type)
            {
                case 1:
                    int regionCode = int.Parse(parts[4]);
                    drinks[count++] = new Tea(id, quantity, price, regionCode);
                    res.Add(drinks[count - 1].CalculateAndDisplayTotalPrice());
                    break;
                case 2:
                    int processingType = int.Parse(parts[4]);
                    drinks[count++] = new Coffee(id, quantity, price, processingType);
                    res.Add(drinks[count - 1].CalculateAndDisplayTotalPrice());
                    break;
                case 3:
                    drinks[count++] = new Milk(id, quantity, price);
                    res.Add(drinks[count - 1].CalculateAndDisplayTotalPrice());
                    break;
            }
        }
        foreach (var x in res)
        {
            Console.WriteLine(x);
        }

    }
}

7-3 C# 3.3 学生信息管理

分数 10

全屏浏览

切换布局

作者 陈卓

单位 青岛科技大学

设计一个学生信息管理控制台应用程序,实现对小学生、中学生、大学生个人姓名、年龄及考试课程成绩的输入,以及平均成绩的统计和显示。功能要求如下:
1)每个学生都有姓名和年龄。
2)小学生有语文、数学成绩。
3)中学生有语文、数学和英语成绩。
4)大学生有必修课学分总数和选修课学分总数,不包含单科成绩。
5)学生类提供向外输出信息的方法。
6)学生类提供统计个人总成绩或总学分的方法。
7)通过静态成员自动记录学生总人数。
8)能通过构造函数完成各字段成员初始化。
提示:
(1) 定义一个抽象学生类:定义受保护字段分别记录学生姓名和年龄,定义公有静态字段记录班级人数。定义一个带两个参数的构造函数,初始化学生姓名和年龄,同时更新班级人数。定义公有只读属性获取学生姓名,定义公有只读虚属性获取学生类型——stuent。定义公有抽象方法计算学生总分。定义公有方法成员返回学生信息字符串。
(2) 定义学生类的派生类小学生类Pupil:定义受保护字段分别记录语文和数学成绩(可为小数),定义带4个参数的构造函数初始化相应字段。重写虚属性获取学生类型——pupil。重写抽象方法计算两门课的平均成绩(保留两位小数)。
(3) 定义学生类的派生类中学生类Middle:定义受保护字段分别记录语文、数学和英语成绩(可为小数),定义带5个参数的构造函数初始化相应字段。重写虚属性获取学生类型——middle school student。重写抽象方法计算三门课的平均成绩(保留两位小数)。
(4) 定义学生类的派生类大学生类College:定义受保护字段分别记录必修课学分和选修课学分(可为小数),定义带4个参数的构造函数初始化相应字段。重写虚属性获取学生类型——college student。重写抽象方法计算总学分(保留两位小数)。
主函数功能:
定义一个小学生一维数组(长度10);根据用户输入的信息,相应建立小学生, 中学生或大学生类对象,用户输入结束后显示学生信息。用户输入的信息的每一行信息格式如下:
第一项为学生类型,小学生为1,中学生为2,大学生为3。
第二项是学生姓名。
第三项是学生年龄。
第四项对小学生和中学生来说是语文成绩;对大学生来说是必修课学分。
第五项对小学生和中学生来说是数学成绩;对大学生来说是选修课学分。
第六项对中学生来说是英语成绩;对小学生和大学生来说没有该项。
当用户输入的一行为0时,表示输入结束。

输入格式:

每个测试用例占一行,用户可输入多行测试用例。当用户输入的一行为0时,表示输入结束。

输出格式:

每一行输出对应用户的一行有效输入,输出学生总人数和该位同学的个人信息。
如果一行中用户输入多个值或一个非零值,且学生类型不属于[1,3],或者学生信息没有按要求给齐,则没有任何输出,统计学生人数时也不统计该学生。
如果用户输入一行为0,则无输出结果。

输入样例:

在这里给出一组输入。例如:

1 a 10 90
2 b 15 90 90 78
3 c 20 19 89
0

输出样例:

在这里给出相应的输出。例如:

Total number of student:2, Name:b, middle school student, Age is 15, AvgScore:86.00;
Total number of student:2, Name:c, college student, Age is 20, TotalCredits :108.00;
using System;
using System.Collections.Generic;

abstract class Student
{
    protected string name;
    protected int age;
    public static int totalStudents = 0;

    public Student(string name, int age)
    {
        this.name = name;
        this.age = age;
        totalStudents++;
    }

    public string Name
    {
        get { return name; }
    }

    public int Age
    {
        get { return age; }
    }

    public abstract string StudentType
    {
        get;
    }

    public abstract double CalculateScore();

    public abstract string GetInfo();
}

class Pupil : Student
{
    protected double chineseScore;
    protected double mathScore;

    public Pupil(string name, int age, double chineseScore, double mathScore) : base(name, age)
    {
        this.chineseScore = chineseScore;
        this.mathScore = mathScore;
    }

    public override string StudentType
    {
        get
        {
            return "pupil";
        }
    }

    public override double CalculateScore()
    {
        return Math.Round((chineseScore + mathScore) / 2.0, 2);
    }

    public override string GetInfo()
    {
        return $"Total number of student:{totalStudents}, Name:{name}, {StudentType}, Age is {age}, AvgScore:{CalculateScore():F2};";
    }
}

class MiddleSchoolStudent : Student
{
    protected double chineseScore;
    protected double mathScore;
    protected double englishScore;
    public MiddleSchoolStudent(string name, int age, double chineseScore, double mathScore, double englishScore) : base(name, age)
    {
        this.chineseScore = chineseScore;
        this.mathScore = mathScore;
        this.englishScore = englishScore;
    }

    public override string StudentType
    {
        get
        {
            return "middle school student";
        }
    }

    public override double CalculateScore()
    {
        return Math.Round((chineseScore + mathScore + englishScore) / 3, 2);
    }

    public override string GetInfo()
    {
        return $"Total number of student:{totalStudents}, Name:{name}, {StudentType}, Age is {age}, AvgScore:{CalculateScore():F2};";
    }
}

class CollegeStudent : Student
{
    protected double requiredCredits;
    protected double electiveCredits;

    public CollegeStudent(string name, int age, double requiredCredits, double electiveCredits): base(name, age)
    {
        this.requiredCredits = requiredCredits; // 必修课学分
        this.electiveCredits = electiveCredits; // 选修课学分
    }

    public override string StudentType { 
        get {
            return "college student"; 
        } 
    }
    public override double CalculateScore()
    {
        return Math.Round(requiredCredits + electiveCredits, 2);
    }

    public override string GetInfo()
    {
        return $"Total number of student:{totalStudents}, Name:{name}, {StudentType}, Age is {age}, TotalCredits :{CalculateScore():F2};";
    }
}

class Program
{
    static void Main(string[] args)
    {
        List<Student> students = new List<Student>();

        while (true)
        {
            string input = Console.ReadLine();
            if (input == "0")
            {
                break;
            }

            string[] parts = input.Split(' ');
            if (parts.Length < 4 || parts.Length > 6) // 长度为 [5, 6] 是合法范围
            {
                continue;
            }

            int studentType; // 必须为 [1, 3]
            if (!int.TryParse(parts[0], out studentType) || studentType < 1 || studentType > 3)
            {
                continue;
            }

            string name = parts[1];
            int age = int.Parse(parts[2]);

            switch (studentType)
            {
                    case 1:
                        if (parts.Length != 5)
                            continue;
                        double chineseScore1 = double.Parse(parts[3]);
                        double mathScore1 = double.Parse(parts[4]);
                        students.Add(new Pupil(name, age, chineseScore1, mathScore1));
                        break;
                    case 2:
                        if (parts.Length != 6)
                            continue;
                        double chineseScore2 = double.Parse(parts[3]);
                        double mathScore2 = double.Parse(parts[4]);
                        double englishScore = double.Parse(parts[5]);
                        students.Add(new MiddleSchoolStudent(name, age, chineseScore2, mathScore2, englishScore));
                        break;
                    case 3:
                        if (parts.Length != 5)
                            continue;
                        double requiredCredits = double.Parse(parts[3]);
                        double electiveCredits = double.Parse(parts[4]);
                        students.Add(new CollegeStudent(name, age, requiredCredits, electiveCredits));
                        break;
             }
        }
        foreach (var student in students)
        {
            Console.WriteLine(student.GetInfo());
        }
    }
}

7-4 C# 3.4 图形类

分数 20

全屏浏览

切换布局

作者 陈卓

单位 青岛科技大学

设计一个求图形面积的控制台应用程序。定义一个抽象类Figure,有一个受保护的常量pi值为3.1415926;有一个抽象成员Area( )可以计算该图形的面积并返回面积值(小数)。定义一个接口IFigure,有一个方法成员Perimeter ( ) 可以计算该图形的周长并返回周长值(小数)。
定义Figure和IFigure的派生类Circle、Rectangle、Triangle。
Circle类有一个私有字段记录半径(小数),有一个带一个参数的构造函数。
Rectangle类有两个私有字段记录长(小数)、宽(小数),有一个带两个参数的构造函数。
Triangle类有三个私有字段记录三条边长(小数),有一个带三个参数的构造函数。
主函数功能:
(1) 读入用户的一行输入。
(2) 根据其中值的个数创建对象或报错:
a) 当输入值个数为1时,如果该值是合理的圆半径(大于0)则创建圆对象;否则报错“Cannot build a circle.”
b) 当输入值个数为2时,如果该值是合理的矩形长、宽值(值都大于0)则创建矩形对象;否则报错“Cannot build a rectangle.”
c) 当输入值个数为3时,如果该值是合理的三角形边的值(值都大于0,任意两边和大于第三边)则创建三角形对象;否则报错“Cannot build a triangle.”
d) 当输入值个数为其他值时,报错“Inputting illegal characters.”,程序结束。
(3) 如果能创建对象,则调用对象的方法求面积和周长,并输出。输出格式如下:
a) Rectangle area is 1.2
b) Rectangle circumference is 2.4
c) Circle area is 3.1415926
d) Circle circumference is 6.2831852
e) Triangle area is 0.433012701892219
f) Triangle circumference is 3

输入格式:

输入一行数据测试数据。

输出格式:

如果输入有效,则第一行输入图形的面积;第二行输出图形的周长。
如果输入无效,则输出一行错误提示。

输入样例:

在这里给出一组输入。例如:

1

输出样例:

在这里给出相应的输出。例如:

Circle area is 3.1415926
Circle circumference is 6.2831852
using System;

abstract class Figure
{
    protected const double pi = 3.1415926;

    public abstract double Area();
}

interface IFigure
{
    double Perimeter();
}

class Circle : Figure, IFigure
{
    private double radius;

    public Circle(double radius)
    { 
        this.radius = radius;
    }

    public override double Area()
    {
        return pi * radius * radius;
    }

    public double Perimeter()
    {
        return 2.0 * pi * radius;
    }
}

class Rectangle : Figure, IFigure
{
    private double length;
    private double width;

    public Rectangle(double length, double width)
    { 
        
        this.length = length;
        this.width = width;
    }

    public override double Area()
    {
        return length * width;
    }

    public double Perimeter()
    {
        return 2.0 * (length + width);
    }
}

class Triangle : Figure, IFigure
{
    private double side1;
    private double side2;
    private double side3;

    public Triangle(double side1, double side2, double side3)
    {
        this.side1 = side1;
        this.side2 = side2;
        this.side3 = side3;
    }

    public override double Area() // 海伦公式
    {
        double s = (side1 + side2 + side3) / 2;
        return Math.Sqrt(s * (s - side1) * (s - side2) * (s - side3));
    }

    public double Perimeter()
    {
        return side1 + side2 + side3;
    }
}

class Program_by_wpc
{
    static void Main(string[] args)
    {
        string input = Console.ReadLine();
        string[] parts = input.Split(' ');
        if(parts.Length == 1)
        {
            double radius = double.Parse(parts[0]);
            if(radius <= 0)
            {
                Console.WriteLine("Cannot build a circle.");
            }
            else
            {
                Circle circle = new Circle(radius);
                Console.WriteLine($"Circle area is {circle.Area()}");
                Console.WriteLine($"Circle circumference is {circle.Perimeter()}");
            }
        }
        else if(parts.Length == 2)
        {
            double length = double.Parse(parts[0]);
            double width = double.Parse(parts[1]);
            if(length <= 0 || width <= 0)
            {
                Console.WriteLine("Cannot build a rectangle.");
            }
            else
            {
                Rectangle rectangle = new Rectangle(length, width);
                Console.WriteLine($"Rectangle area is {rectangle.Area()}");
                Console.WriteLine($"Rectangle circumference is {rectangle.Perimeter()}");
            }
        }
        else if(parts.Length == 3)
        {
            double edge1 = double.Parse(parts[0]);
            double edge2 = double.Parse(parts[1]);
            double edge3 = double.Parse(parts[2]);
            if(edge1 <= 0 || edge2 <= 0 || edge3 <= 0 || (edge1 + edge2 <= edge3) || (edge1 + edge3 <= edge2) || (edge2 + edge3 <= edge1))
            {
                Console.WriteLine("Cannot build a triangle.");
            }
            else
            {
                Triangle triangle = new Triangle(edge1, edge2, edge3);
                Console.WriteLine($"Triangle area is {triangle.Area()}");
                Console.WriteLine($"Triangle circumference is {triangle.Perimeter()}");
            }
        }
        else
        {
            Console.WriteLine("Inputting illegal characters.");
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值