Go语言编程快速入门:P04 循环分支

P04 循环分支
更新于: 2022-01-15 07:50:06

比较

true/false

  1. ==
  2. ≤/</>/≥

利用if/else 做分支

正常语法:if---else if---else ----

switch--case--default: 不需要break

package main

import (
	"fmt"
)

func main() {
	const score = 85
	if score > 90 && score < 100 {
		fmt.Println("Xiu")
	} else {
		fmt.Println("Not xiu")
	}
}
package main

import (
	"fmt"
)

func main() {
	const score = 85
	switch true {
	case score < 90:
		fmt.Println("Not Xiu")
	case score > 80 && score <= 90:
		fmt.Println("Good")
	default:
		fmt.Println("Hurry up.")
	}
}

switch--fallthrough关键字

默认可以继续执行下个case里的内容

package main

import (
	"fmt"
)

func main() {
	const score = 85
	switch true {
	case score > 85 && score <= 90:
		fmt.Println("Good")
	case score < 90:
		fmt.Println("Not Xiu")
		fallthrough
	case score != 0:
		fmt.Println("Good stu.")
	default:
		fmt.Println("Hurry up.")
	}
}

for 循环/break/continue

package main

import "fmt"

func main() {
	var count = 10

	for count > 0 {
		fmt.Println("count value: %v", count)
		count--
	}
}

作业

随机生成100个数,与自己的数比较,看是大了,还是小了

package main

import (
	"fmt"
	"math/rand"
)

func main() {
	var mynum = 45
	var times = 100

	for i := 0; i < times; i++ {
		var tar = rand.Intn(101)
		fmt.Println()
		if tar == mynum {
			fmt.Printf("ok")
		} else if tar < mynum {
			fmt.Printf("small than my num %v", tar)
		} else {
			fmt.Printf("big than my num %v", tar)
		}
	}

}

参考