條件語句通過指定一個(gè)或多個(gè)條件,并通過測(cè)試條件是否為 true 來決定是否執(zhí)行指定語句,并在條件為 false 的情況在執(zhí)行另外的語句
if語句
if 語句由布爾表達(dá)式后緊跟一個(gè)或多個(gè)語句組成。語法如下:
if 布爾表達(dá)式 {
/* 在布爾表達(dá)式為 true 時(shí)執(zhí)行 */
}
if 在布爾表達(dá)式為 true 時(shí),其后緊跟的語句塊執(zhí)行,如果為 false 則不執(zhí)行。
package main
import "fmt"
func main() {
a := 10
if a < 20 {
fmt.Printf("a 小于 20\n")
}
if a > 20 {
fmt.Printf("a 大于 20\n")
}
fmt.Printf("a 的值為: %d\n", a)
}
if...else語句
語法如下:
if 布爾表達(dá)式 {
/* 在布爾表達(dá)式為 true 時(shí)執(zhí)行 */
} else {
/* 在布爾表達(dá)式為 false 時(shí)執(zhí)行 */
}
if 在布爾表達(dá)式為 true 時(shí),其后緊跟的語句塊執(zhí)行,如果為 false 則執(zhí)行 else 語句塊。
package main
import "fmt"
func main() {
a := 30
if a < 20 {
fmt.Printf("a 小于 20\n")
} else {
fmt.Printf("a 大于等于 20\n")
}
fmt.Printf("a 的值為: %d\n", a)
}
else if語句
if 布爾表達(dá)式 1 {
/* 在布爾表達(dá)式 1 為 true 時(shí)執(zhí)行 */
} else if 布爾表達(dá)式 2 {
/* 在布爾表達(dá)式 2 為 true 時(shí)執(zhí)行 */
} else {
/* 默認(rèn)時(shí)執(zhí)行 */
}
示例:
package main
import "fmt"
func main() {
a := 80
if a > 90 {
fmt.Printf("a 的值為%d,它大于等于90", a)
} else if a > 80 {
fmt.Printf("a 的值為%d,它大于等于80", a)
} else if a >= 60 {
fmt.Printf("a 的值為%d,它大于等于60", a)
} else {
fmt.Printf("a 的值為%d,它小于60", a)
}
}
練習(xí):
package main
import "fmt"
func main() {
var yes string
fmt.Print("有賣西瓜的嗎:[Y/N] ")
fmt.Scan(&yes)
fmt.Println("老婆的想法: ")
fmt.Println("十個(gè)包子")
// if
if yes == "Y" || yes == "y" {
fmt.Println("一個(gè)西瓜")
}
// if else
fmt.Println("老公的想法: ")
if yes == "Y" || yes == "y" {
fmt.Println("一個(gè)包子")
} else {
fmt.Println("十個(gè)包子")
}
// if 多分支
var score int
fmt.Print("請(qǐng)輸入分?jǐn)?shù): ")
fmt.Scan(&score)
if score >= 90 {
fmt.Println("A")
} else if score >= 80 {
fmt.Println("B")
} else if score >= 70 {
fmt.Println("C")
} else if score >= 60 {
fmt.Println("D")
} else {
fmt.Println("E")
}
}