• 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

  • 相关阅读:
    Brackets_区间DP
    石子合并_区间Dp
    You Are the One_区间DP
    Palindrome subsequence_区间DP
    Infix to postfix 用stack模板,表达式没有括号
    Java 4
    Java 3
    规范化的递归转换成非递归
    recursion 递归以及递归的缺点
    Infix to postfix conversion 中缀表达式转换为后缀表达式
  • 原文地址:https://www.cnblogs.com/gongxiaokai/p/7123797.html
Copyright © 2020-2023  润新知