1、设计控制台应用程序,声明一个人类Person和一个动物类Animal,它们都包含有公有字段legs(腿的数目)和保护字段weight(重量),定义它们的对象并输出相关数据。
using System;
namespace Test3_1
{
public class Person
{
public int legs;
protected double weight;
public Person() { }
public Person(int legs1, double weight1)
{
legs = legs1;
weight = weight1;
}
public void show()
{
Console.WriteLine("某人有{0}只腿,重量为{1}kg", legs, weight);
}
}
class Animal
{
public int legs;
protected double weight;
public Animal() { }
public Animal(int legs2, double weight2)
{
legs = legs2;
weight = weight2;
}
public void show()
{
Console.WriteLine("某动物有{0}只脚,重量为{1}kg", legs, weight);
}
}
class Program
{
static void Main(string[] args)
{
Person p = new Person(2, 50);
Animal a = new Animal(4, 120);
p.show();
a.show();
}
}
}
运行结果:
2、设计控制台应用程序,输入若干个学生的英语和数学成绩,求出总分,并按总分从高到低排序,要求设计一个学生类Student,所有学生对象存放在一个Student对象数组中,通过一个方法对其按照总分进行降序排序,最后输出排序后的结果。
using System;
namespace Test3_2
{
public class Student
{
private string name;
private int english, math, sum;
public int p_sum
{
get { return sum; }
}
public void Data()
{
Console.Write("姓名:");
name = Console.ReadLine();
Console.Write("英语:");
english = int.Parse(Console.ReadLine());
Console.Write("数学:");
math = int.Parse(Console.ReadLine());
sum = english + math;
}
public void display()
{
Console.WriteLine("\t{0}\t{1}\t{2}\t{3}", name, english, math, sum);
}
}
class Program
{
const int Max = 100;
static void sort(int n, params Student[] p)
{
int i, j;
bool A;
Student t;
for (i = 0; i < n - 1; i++)
{
A = false;
for (j = n - 2; j >= i; j--)
if (p[j + 1].p_sum > p[j].p_sum)
{
t = p[j + 1];
p[j + 1] = p[j];
p[j] = t;
A = true;
}
if (A == false)
break;
}
}
static void Main(string[] args)
{
int n, i;
Student[] p = new Student[Max]; //定义对象引用数组
Console.Write("n:");
n = int.Parse(Console.ReadLine());
for (i = 0; i < n; i++) //创建对象引用的实例
p[i] = new Student();
for (i = 0; i < n; i++)
{
Console.WriteLine("请输入第{0}个学生数据:", i + 1);
p[i].Data();
}
Console.WriteLine("排序前:");
Console.WriteLine("\t姓名\t英语\t数学\t总分");
for (i = 0; i < n; i++)
{
Console.Write("序号{0}", i + 1);
p[i].display();
}
sort(n, p); //按总成绩降序排序
Console.WriteLine("排序后:");
Console.WriteLine("\t姓名\t英语\t数学\t总分");
for (i = 0; i < n; i++)
{
Console.Write("第{0}名:", i + 1);
p[i].display();
}
}
}
}
运行结果: