swift3.0 基礎練習-構造對象並按要求進行排序(struct)


struct練手
構造10個學生(要求有學生的姓名、數學成績、英語成績),按照學生英語和數學平均分的成績從小到大輸出學生的姓名、數學成績、英語成績及平均分
創建一個學生構造體,包含 姓名 name 數學成績 mathScore英語成績 englishScore 平均分average 並在創建時求出平均分

struct Student{
    var name:String
    var mathScore:Int
    var englishScore:Int
    var average:Float

        //MARK: - 初始化並求平均值
    init(name:String,mathScore:Int,englishScore:Int) {
        self.name = name
        self.mathScore = mathScore
        self.englishScore = englishScore
        self.average = Float(self.mathScore + self.englishScore) / 2
    }
}

排序我這里使用的是喜聞樂見的冒泡法

func sortWithAverage(students:[Student]) -> [Student] {
        var result = students
        for i in 0..<result> result[j].average) {
                    let tmp = result[i]
                    result[i] = result[j]
                    result[j] = tmp
                }
            }
        }
        return result
    }

下面我們來構造對象並輸出結果

//構造10個學生對象
var student01 = Student(name: "st01", mathScore: 67, englishScore: 98)
var student02 = Student(name: "st02", mathScore: 87, englishScore: 56)
var student03 = Student(name: "st03", mathScore: 47, englishScore: 86)
var student04 = Student(name: "st04", mathScore: 65, englishScore: 88)
var student05 = Student(name: "st05", mathScore: 85, englishScore: 97)
var student06 = Student(name: "st06", mathScore: 85, englishScore: 94)
var student07 = Student(name: "st07", mathScore: 92, englishScore: 76)
var student08 = Student(name: "st08", mathScore: 93, englishScore: 66)
var student09 = Student(name: "st09", mathScore: 63, englishScore: 93)
var student10 = Student(name: "st10", mathScore: 99, englishScore: 82)

//調用排序方法
var result = sortWithAverage(students: [student01,
                                        student02,
                                        student03,
                                        student04,
                                        student05,
                                        student06,
                                        student07,
                                        student08,
                                        student09,
                                        student10])

print("英語和數學平均分的成績從小到大排列為:")
//遍歷結果數組並打印
for i in 0..<result.count{
    print("姓名:\(result[i].name),數學成績:\(result[i].mathScore),英語成績:\(result[i].englishScore),平均分:\(result[i].average)")
}

結果就出來了

struct.png


注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
粤ICP备14056181号  © 2014-2020 ITdaan.com