/** * 第 3 章 · 实战案例 — 学生成绩等级判定器 * * 综合演示了: * - when 表达式 * - 范围 (in 0..100) * - 字符串模板 * - for + withIndex * - 函数定义 * * 业务场景:教务系统给一批学生算成绩等级。 */ data class Student(val name: String, val score: Int) fun grade(score: Int): String = when { score !in 0..100 -> "无效分数" score >= 90 -> "A" score >= 80 -> "B" score >= 70 -> "C" score >= 60 -> "D" else -> "F" } fun comment(score: Int): String = when (score) { in 90..100 -> "优秀!继续保持 🎉" in 80..89 -> "良好,下次冲一冲 💪" in 70..79 -> "中等,还有提升空间" in 60..69 -> "刚及格,要加把劲!" in 0..59 -> "不及格,需要补课 😢" else -> "分数无效,请检查输入" } fun main() { val students = listOf( Student("Alice", 95), Student("Bob", 82), Student("Charlie", 73), Student("David", 60), Student("Eve", 45), Student("Frank", 105), ) println("=== 学生成绩单 ===") println("%-10s %-6s %-6s %s".format("姓名", "分数", "等级", "评语")) println("-".repeat(50)) for (s in students) { val g = grade(s.score) val c = comment(s.score) println("%-10s %-6d %-6s %s".format(s.name, s.score, g, c)) } println("\n=== 班级统计 ===") val valid = students.filter { it.score in 0..100 } val avg = valid.map { it.score }.average() val max = valid.maxByOrNull { it.score } val min = valid.minByOrNull { it.score } val passed = valid.count { it.score >= 60 } println("有效人数: ${valid.size}") println("平均分: ${"%.1f".format(avg)}") println("最高分: ${max?.name} ${max?.score}") println("最低分: ${min?.name} ${min?.score}") println("及格率: ${"%.0f%%".format(passed * 100.0 / valid.size)}") }