Golang學習筆記(七)if判斷語句
阿新 • • 發佈:2018-11-05
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("不及格") } }