作业 - 排序

main.swift

 1 import Foundation
 2 struct Students//设置结构体 Student
 3 {
 4     var name:String
 5     var math:Int
 6     var english:Int
 7 
 8     init(name:String="NULL",math:Int=0,english:Int=0){ //设置结构体默认值
 9         self.name=name
10         self.math=math
11         self.english=english
12     }
13     
14     func toString() -> String { //设置结构体函数
15         return "\(self.name)的平均分是 \((self.math+self.english)/2),数学:\(self.math),英语:\(self.english),"
16     }
17 }
18 
19 //声明十个结构体变量
20 var s0=Students(name: "HSAD", math: 79, english: 97)
21 var s1=Students(name: "IIQW", math: 81, english: 48)
22 var s2=Students(name: "WUIQ", math: 83, english: 49)
23 var s3=Students(name: "ISAD", math: 94, english: 40)
24 var s4=Students(name: "OEHR", math: 57, english: 49)
25 var s5=Students(name: "UGUE", math: 59, english: 10)
26 var s6=Students(name: "RTUB", math: 95, english: 58)
27 var s7=Students(name: "OTRW", math: 59, english: 58)
28 var s8=Students(name: "IEFF", math: 90, english: 69)
29 var s9=Students(name: "EGDB", math: 60, english: 59)
30 
31 var stu = [s0,s1,s2,s3,s4,s5,s6,s7,s8,s9]//组成数组
32 
33 var tmp = stu[0]//设置暂存的变量
34 for b in 0...8//设置排序
35 {
36     for a in 0...(8-b)
37     {
38         if (stu[a].math+stu[a].english)>=(stu[a+1].math+stu[a+1].english)
39         {
40             tmp = stu[a]
41             stu[a]=stu[a+1]
42             stu[a+1]=tmp
43         }
44     }
45     
46 }
47 
48 for a in 0...9 //设置输出
49 {
50     print(stu[a].toString())
51 }

 

posted @ 2016-05-09 13:03  小样和牛牛  阅读(160)  评论(0编辑  收藏  举报