go language to guess the number of small game method

  • 2020-05-26 09:21:40
  • OfStack

The example of this article describes the go language to achieve the number of guessing game method. Share with you for your reference. The specific analysis is as follows:

Randomly generate 1 number, input 1 number to see if it is matched, matching will be the knot speed, otherwise it will indicate whether it is larger or smaller

package main
import (
    "bufio"
    "fmt"
    "math/rand"
    "os"
    "strconv"
    "time"
)
var (
    endNum int // Sets the range of the generated number
)
func main() {
    i := createRandomNumber(endNum)
    //fmt.Println(" Generates an integer in the specified range :", i)    // This sentence is used for debugging
    fmt.Println(" Please enter an integer , The range of :0-", endNum)
    flag := true
    reader := bufio.NewReader(os.Stdin)
    for flag {
        data, _, _ := reader.ReadLine()
        command, err := strconv.Atoi(string(data)) //string to int, And make input format judgment
        if err != nil {
            fmt.Println(" Incorrect format, please enter a number ")
        } else {
            fmt.Println(" The number you entered :", command)
            if command == i {
                flag = false
                fmt.Println(" Congratulations, that's right ~")
            } else if command < i {
                fmt.Println(" The number you entered is smaller than the number generated. Don't despair! Come again 1 time ~")
            } else if command > i {
                fmt.Println(" The number you entered is greater than the number generated. Don't despair! Come again 1 time ~")
            }
        }
    }
}
func init() {
    endNum = 10
}
// Generates an integer in the specified range
// Set the starting number range, 0 start ,endNum As of
func createRandomNumber(endNum int) int {
    r := rand.New(rand.NewSource(time.Now().UnixNano()))
    return r.Intn(endNum)
}

I hope this article has been helpful to your programming of Go language.


Related articles: