Golang学习笔记(七)if判断语句

版权声明:如需转载、粘贴内容,必须在转载和粘贴文中标明文章内容出至 https://blog.csdn.net/ynzcxx/article/details/83621327

golang的判断语句,不再需要用()来括起条件,但{必须跟if在一行。和java一样,也有else关键字。

基础例子,判断奇偶数,给出一个值30,让程序来判断。

func EvenOdd(){
	num := 30
	if num % 2 == 0 {
		fmt.Println(num,"这是个偶数")
	} else {
		fmt.Println(num,"这是个奇数")
	}
}

接着来一个if.....else if....else.....的例子

func ScoreMark1() {
	score := 78
	if score >= 90 {
		fmt.Println("优秀")
	} else if score >= 80{
		fmt.Println("良好")
	} else if score >= 70{
		fmt.Println("中等")
	} else 	if score >= 60 {
		fmt.Println("及格")
	} else {
		fmt.Println("不及格")
	}
}

上面这个例子,所有的数值不能反,只能由大而小的执行。

为了改善上面的这个例子,用if嵌套来写新的例子。

func ScoreMark2() {
	score := 78
	if score >= 60 {
		if score >= 70 {
			if score >= 80 {
				if score >= 90 {
					fmt.Println("优秀")
				} else {
					fmt.Println("良好")
				}
			} else {
				fmt.Println("中等")
			}
		} else {
			fmt.Println("及格")
		}
	} else {
		fmt.Println("不及格")
	}
}

猜你喜欢

转载自blog.csdn.net/ynzcxx/article/details/83621327
今日推荐