Go语言实现猜数字游戏
Posted 做1个快乐的程序员
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Go语言实现猜数字游戏相关的知识,希望对你有一定的参考价值。
Go和C有很多语法相近,但是也有很大区别,像变量的命名以及很多标准库的引用,这里用Go语言实现了猜数字游戏。
package main
import (
"bufio"
"fmt"
"math/rand"
"os"
"strconv"
"strings"
"time"
)
func main()
maxNum := 100
rand.Seed(time.Now().UnixNano()) //用时间戳来初始化随机数种子
secretNumber := rand.Intn(maxNum)
fmt.Println("The secret number is ", secretNumber)
fmt.Println("Please input your guess")
reader := bufio.NewReader(os.Stdin)
for
input, err := reader.ReadString('\\n') //读取一行输入
if err != nil
fmt.Println("An error occured while reading input. Please try again", err)
continue
input = strings.TrimSuffix(input, "\\n") //去掉换行符
guess, err := strconv.Atoi(input) //转换成数字
if err != nil
fmt.Println("Invalid input. Please enter an integer value")
continue
fmt.Println("You guess is", guess)
if guess > secretNumber
fmt.Println("Your guess is bigger than the secret number. Please try again")
else if guess < secretNumber
fmt.Println("Your guess is smaller than the secret number. Please try again")
else
fmt.Println("Correct, you Legend!")
break
以上是关于Go语言实现猜数字游戏的主要内容,如果未能解决你的问题,请参考以下文章