C# 之 結構體(struct)---複合型別的資料結構
阿新 • • 發佈:2018-12-26
例題:
/*建立學生結構體,輸出最高分數*/ /*使用結構體陣列 -----複合型別(string int float等) student[] students=new student[5]; */ //定義一個結構體 struct student { //年齡 前面加了 public是訪問修飾符 為所有成員都有訪問級別; public string name; public int age; public string sno; public float score; //建立一個結構體建構函式 public student(string name1, int age1, string sno1, float score1) { this.name = name1; this.age = age1; this.sno = sno1; this.score = score1; } } public void scorehigh() { //宣告一個結構體陣列 student[] stu = new student[5]; //第一種方法 直接new 分配呼叫建構函式 //stu[0] = new student("Deng",19, "51388938", 90); //stu[1] = new student("Han", 20, "51388932", 90); //stu[2] = new student("Piao",20, "51388934", 90); //stu[3] = new student("Jia", 19, "51388935", 90); //stu[4] = new student("Xia", 21, "51388933", 90); //第二種方法 建立不同型別的陣列 string[] name = { "Deng", "Han", "Piao", "Jia", "Xia" };//姓名 int[] age = {19,20,20,19,18};//年齡 float maxscore = 0; int maxindex=0; float[] score = { 90, 91, 93, 95, 78 }; for (int i = 0; i < stu.Length; i++) { //賦值過程 stu[i] = new student(name[i], age[i], "510234", score[i]); if (stu[i].score > maxscore) { maxscore = stu[i].score; maxindex = i; } } Console.WriteLine("分數最高:"+stu[maxindex].score); }