Go if 条件判断,switch 语句

demo.go(if 条件判断):

package main

import "fmt"

func main() {

	var score int = 500

	// if条件判断
	if score<450 {
		fmt.Println("哈哈")
	} else if score<550 {
		fmt.Printf("你好")
	} else {
		fmt.Printf("你好2")
	}

}

demo.go(switch语句):

package main

import "fmt"

func main() {

	var score int = 85

	// switch语句
	switch score / 10 {
	case 10:
		fmt.Println("优秀") // go语言中不需要添加 break
	case 9:
		fmt.Println("优秀")
	case 8:
		fmt.Println("良好")
	case 7:
		fmt.Println("中等")
	case 6:
		fmt.Println("及格")
	default:
		fmt.Println("不及格")
	}

	// switch 第二种方式(执行速度没有上面方式快)
	switch {
	case score >= 90:
		fmt.Println("优秀")
	case score >= 80:
		fmt.Println("良好")
	case score >= 70:
		fmt.Println("中等")
	case score >= 60:
		fmt.Println("及格")
	default:
		fmt.Println("不及格")
	}


	switch score / 10 {
	case 10, 9, 8, 7, 6:   // 可以将多种情况放到一个case中
		fmt.Println("及格")
	default:
		fmt.Println("不及格")
	}

	// fallthrough表示进入下一个case继续执行
	switch score / 10 {
	case 10:
		fallthrough
	case 9:
		fallthrough
	case 8:
		fallthrough
	case 7:
		fallthrough
	case 6:
		fmt.Println("及格")
	default:
		fmt.Println("不及格")
	}

}

猜你喜欢

转载自blog.csdn.net/houyanhua1/article/details/88605559