package main
import "fmt"
func main() {
s1 := "3"
s2 := "12"
//直接比较时,从左至右逐个字符根据ASCII码值大小比较,会出错
if s1 > s2 {
fmt.Println("直接比较结果:", s1, ">", s2)
}
//优化比较,先比较位数再比较大小
if len(s1) == len(s2) {
if s1 > s2 {
fmt.Println("优化比较结果:", s1, ">", s2)
} else {
fmt.Println("优化比较结果:", s1, "<=", s2)
}
} else {
if len(s1) > len(s2) {
fmt.Println("优化比较结果:", s1, ">", s2)
} else {
fmt.Println("优化比较结果:", s1, "<=", s2)
}
}
}
运行结果如下:
直接比较结果: 3 > 12
优化比较结果: 3 <= 12Process finished with exit code 0