How to resolve the algorithm Guess the number/With feedback step by step in the Go programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Guess the number/With feedback step by step in the Go programming language
Table of Contents
Problem Statement
Write a game (computer program) that follows the following rules:
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Guess the number/With feedback step by step in the Go programming language
This Go program implements a number guessing game.
The program first generates a random integer between 1 and 100 using the rand.Intn
function.
It then prompts the user to guess the number and stores the user's guess in the variable guess
.
The program then compares the user's guess to the randomly generated number and prints a message to the user indicating whether the guess is too low, too high, or correct.
If the guess is correct, the program prints a congratulatory message and exits.
If the guess is incorrect, the program prompts the user to guess again.
The program continues to loop until the user guesses the correct number.
Source code in the go programming language
package main
import (
"fmt"
"math/rand"
"time"
)
const lower, upper = 1, 100
func main() {
fmt.Printf("Guess integer number from %d to %d: ", lower, upper)
rand.Seed(time.Now().Unix())
n := rand.Intn(upper-lower+1) + lower
for guess := n; ; {
switch _, err := fmt.Scan(&guess); {
case err != nil:
fmt.Println("\n", err, "So, bye.")
return
case guess < n:
fmt.Print("Too low. Try again: ")
case guess > n:
fmt.Print("Too high. Try again: ")
default:
fmt.Println("Well guessed!")
return
}
}
}
You may also check:How to resolve the algorithm Non-decimal radices/Convert step by step in the Fortran programming language
You may also check:How to resolve the algorithm Optional parameters step by step in the Mathematica/Wolfram Language programming language
You may also check:How to resolve the algorithm Top rank per group step by step in the REXX programming language
You may also check:How to resolve the algorithm Operator precedence step by step in the 8th programming language
You may also check:How to resolve the algorithm Check that file exists step by step in the Scheme programming language