【基础入门题】Golang 004. 转换百分制分数
给出一个百分制成绩,要求输出等级为A,B,C,D,E。
90分以上即n>=90为A;80<=n<90分为B;以此类推;
直到n<60分全为E;如果输入小于0或大于100的分数,
则输出“Not valid”。
输入形式:输入一个可能带小数点的分数
输出形式:根据对应关系,输出五分制分数档。
方法一: if - else if - else
package main import "fmt" func Grade(m float32) string { var result string if m <= 100 && m >= 90 { result = "A" } else if m < 90 && m >= 80 { result = "B" } else if m < 80 && m >= 70 { result = "C" } else if m < 70 && m >= 60 { result = "D" } else if m < 60 && m >= 0 { result = "E" } else { result = "Not valid" } return result } func main() { fmt.Printf("Grade(%.1f) = %s\n", 80.5, Grade(80.5)) fmt.Printf("Grade(%d) = %s\n", 100, Grade(100)) fmt.Printf("Grade(%d) = %s\n", 105, Grade(105)) /* Out: Grade(80.5) = B Grade(100) = A Grade(105) = Not valid */ }
方法二: switch - case - default,switch后无表达式
package main import "fmt" func Grade(m float32) string { var result string switch { case m <= 100 && m >= 90: result = "A" case m < 90 && m >= 80: result = "B" case m < 80 && m >= 70: result = "C" case m < 70 && m >= 60: result = "D" case m < 60 && m >= 0: result = "E" default: result = "Not valid" } return result } func main() { fmt.Printf("Grade(%.1f) = %s\n", 80.5, Grade(80.5)) fmt.Printf("Grade(%d) = %s\n", 100, Grade(100)) fmt.Printf("Grade(%d) = %s\n", 105, Grade(105)) /* Out: Grade(80.5) = B Grade(100) = A Grade(105) = Not valid */ }
方法三: switch - case - default,switch后有表达式
package main import "fmt" func Grade(m float32) string { var result string if m > 100 || m < 0 { return "Not valid" } switch int(m) / 10 { case 10, 9: result = "A" case 8: result = "B" case 7: result = "C" case 6: result = "D" default: result = "E" } return result } func main() { fmt.Printf("Grade(%.1f) = %s\n", 80.5, Grade(80.5)) fmt.Printf("Grade(%d) = %s\n", 100, Grade(100)) fmt.Printf("Grade(%d) = %s\n", 105, Grade(105)) }