4 流程控制
1 if 语句
package main import ( "fmt" "strconv" ) func test(a int) (res string) { if a>=90{ res = "优" }else if a>=80{ res = "良" }else if a >=70{ res = "中" }else if a >=60{ res = "差" }else{ res = "不及格" } return } func test01() { var a string fmt.Scanf("%s",&a) res,err := strconv.Atoi(a) if err != nil{ fmt.Println("convert to int err",err) }else{ fmt.Println("you enter is ",res) } } func main() { var a = 55 fmt.Println(test(a)) }
2 switch语句
package main import "fmt" func switch1() { var a = 0 switch a{ case 0: fmt.Println("a is equal 0") //fallthrough //fallthrough 关键字可以让程序继续往下走 case 10: fmt.Println("a is equal 10") default: fmt.Println("a is equal other") } } func switch2() { var a = 3 switch a{ case 0,1,2,3,4,5: fmt.Println("a equal 0-5") case 10: fmt.Println("a equal 10") default: fmt.Println("other") } } func switch3(){ var a = 10 switch { case a >0 && a<10: fmt.Println("a>0 and a<10") case a>=10 && a<20: fmt.Println("a>=10 and a <20") default: fmt.Println("other") } } func main() { switch3() }
4 猜数字
package main import ( "fmt" "math/rand" ) func main() { var num = rand.Intn(100) var a int for{ fmt.Scanf("%d",&a) if isOk(num,a){ break } } } func isOk(num,a int) (result bool){ switch { case a>num: fmt.Println("大了") result = false case a < num: fmt.Println("小了") result = false default: fmt.Println("猜对了,随机的数字是",num) result = true } return }
5 for循环 for range
package main import "fmt" func main() { //var a = 5 //for i := 1; i <=a; i++ { // test01(i) //} test04() } //for range语句 可以用来遍历数组,slice,map,chan func test04() { str := "hello world" for _,v := range str{ fmt.Printf("%c\n",v) } } //无限循环 func test02() { for true{ } for { fmt.Println("xxx") } } //for 实现while循环 func test03() { var i = 5 for i>0{ fmt.Println(i) i-- } } func test01(num int) { for i:=1;i<=num;i++{ fmt.Print("★") } fmt.Println() }