Skip to content

Instantly share code, notes, and snippets.

@zeuxisoo
Last active September 25, 2019 21:42
Show Gist options
  • Save zeuxisoo/c308af636aba47ecbca9c21bd373b6e0 to your computer and use it in GitHub Desktop.
Save zeuxisoo/c308af636aba47ecbca9c21bd373b6e0 to your computer and use it in GitHub Desktop.
A simple program ask user to guess the number
package main
import (
"os"
"fmt"
"bufio"
"strings"
"strconv"
"time"
"math/rand"
)
func init() {
rand.Seed(time.Now().UnixNano())
}
func askForInput(question string) (int, error) {
AskAgain:
fmt.Print(question)
text, _ := bufio.NewReader(os.Stdin).ReadString('\n')
if i, err := strconv.Atoi(strings.TrimSpace(text)); err != nil {
printTips("Please enter number not string")
goto AskAgain
}else{
return i, nil
}
}
func printTips(text string) {
fmt.Printf("\n=> %s\n\n" ,text)
}
func main() {
numberA, _ := askForInput("Please enter 1st number: ")
numberB, _ := askForInput("Please enter 2nd number: ")
differenceNumber := numberB - numberA
answerNumber := numberA + (rand.Int() % (differenceNumber + 1))
printTips(fmt.Sprintf("numberA=%d, numberB=%d, difference=%d, answer=%d", numberA, numberB, differenceNumber, answerNumber))
for ;; {
guessNumber, _ := askForInput("Please guess the answer: ")
if guessNumber < numberA || guessNumber > numberB {
printTips(fmt.Sprintf("The guess number out of range"))
continue
}
if guessNumber == answerNumber {
break
}
if (guessNumber >= answerNumber && guessNumber <= numberB) {
numberB = guessNumber
}
if (guessNumber >= numberA && guessNumber <= answerNumber) {
numberA = guessNumber
}
printTips(fmt.Sprintf("New range: %d to %d", numberA, numberB))
}
printTips(fmt.Sprintf("You win! The answer is %d", answerNumber))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment