Skip to content

Instantly share code, notes, and snippets.

@mhewedy
Created February 12, 2022 14:52
Show Gist options
  • Select an option

  • Save mhewedy/5136686c5355b0ea700673bce9bb2d1e to your computer and use it in GitHub Desktop.

Select an option

Save mhewedy/5136686c5355b0ea700673bce9bb2d1e to your computer and use it in GitHub Desktop.
package main
import (
    "fmt"
    "math/rand"
    "os"
    "os/signal"
    "time"
)
func main() {
    rand.Seed(time.Now().UnixNano())
    score := 0
    total := 0
    c := make(chan os.Signal, 1)
    signal.Notify(c, os.Interrupt)
    go func() {
        for range c {
            fmt.Printf("\n\nYou got %d out of %d \n", score, total)
            os.Exit(0)
        }
    }()
    for {
        answer := rand.Intn(999-1) + 1
        var nearest int
        if rand.Intn(2) == 1 {
            nearest = 10
        } else {
            nearest = 100
        }
        // 1. Prompt
        fmt.Printf("Enter your guess for %d (nearest %d): ", answer, nearest)
        // 2. Read input
        var guess int
        fmt.Scanf("%d", &guess)
        // 3. Processing
        tmp1 := ((answer / nearest) + 1) * nearest
        tmp2 := (answer / nearest) * nearest
        var result int
        if (tmp1 - answer) > (answer - tmp2) {
            result = tmp2
        } else {
            result = tmp1
        }
        // 4. Output
        if result == guess {
            score++
            fmt.Println("herray! you are correct")
        } else {
            fmt.Printf("Ohh! the result is: %d", result)
        }
        total++
        fmt.Println("----------------")
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment