標籤:
class Program { struct student { public string name; public int code; public int age; public double fenshu; } static void Main(string[] args) { ArrayList al = new ArrayList(); //定義一個新的集合 Console.Write("請輸入人數:"); int renshu = Convert.ToInt32(Console .ReadLine ()); for (int i = 0; i <renshu; i++) { student r = new student(); Console.Write("請輸入第"+(i+1)+"個人的名字:"); r.name = Console.ReadLine(); Console.Write("請輸入第" + (i + 1) + "個人的學號:"); r.code = Convert.ToInt32(Console .ReadLine ()); Console.Write("請輸入第" + (i + 1) + "個人的年齡:"); r.age = Convert.ToInt32(Console .ReadLine ()); Console.Write("請輸入第" + (i + 1) + "個人的分數:"); r.fenshu = Convert.ToDouble(Console .ReadLine ()); al.Add(r); //把r的資料都放在al這個集合裡 } ; for (int i = 0; i < renshu ; i++) { for (int j = i; j < renshu-1; j++) if (((student)al[i]).fenshu<((student )al[j+1]).fenshu) //從student 結構體的集合裡調出分數進行比較 { student zhong; zhong = (student )al[i]; al[i] = al[j + 1]; al[j+ 1] = zhong; } } Console .WriteLine ("排序後學生順序:"); for (int i = 0; i < renshu; i++) { Console.WriteLine("名字\t" + ((student)al[i]).name + "學號\t" + ((student)al[i]).code + "年齡\t" + ((student)al[i]).age + "分數\t" + ((student)al[i]).fenshu ); } Console.ReadLine(); } } }
C#例題:輸入學生學號,姓名,分數,然後根據分數進行排序。這個題是用集合和結構體來做,與上一題不同。掌握基礎知識很重要