猜数字游戏,用到了生成随机数
1 package main 2 3 import ( 4 "fmt" 5 "math/rand" 6 "strconv" 7 "time" 8 ) 9 10 func main() { 11 //生成一个随机数 12 myRand := rand.New(rand.NewSource(time.Now().UnixNano())) 13 answer := myRand.Intn(1000) 14 15 fmt.Println("按Q可退出") 16 17 for { 18 19 //接收用户的输入 20 fmt.Println("请输入你的猜想: ") 21 22 var guess string 23 fmt.Scan(&guess) 24 25 //用户想要提前退出 26 if guess == "q" || guess == "Q" { 27 break 28 } 29 30 //用户的输入转换成整数 31 guessNum, _ := strconv.Atoi(guess) 32 33 //反馈猜测的结果 34 switch { 35 case guessNum > answer: 36 fmt.Println(guessNum,"太大了....") 37 case guessNum < answer: 38 fmt.Println(guessNum,"太小了....") 39 default: 40 fmt.Println("没错,我让你猜的就是",guessNum) 41 break 42 } 43 } 44 }