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();
}
}
}
}
運行結果: