create a calculator in go

You can create a simple calculator in Go using the built-in fmt and strconv packages. Here's a basic implementation:

main.go
package main

import (
    "fmt"
    "strconv"
)

func main() {
    var num1, num2 float64
    var operation string

    fmt.Print("Enter first number: ")
    fmt.Scanln(&num1)

    fmt.Print("Enter second number: ")
    fmt.Scanln(&num2)

    fmt.Print("Enter operation (+, -, *, /): ")
    fmt.Scanln(&operation)

    switch operation {
    case "+":
        fmt.Println(num1, "+", num2, "=", num1+num2)
    case "-":
        fmt.Println(num1, "-", num2, "=", num1-num2)
    case "*":
        fmt.Println(num1, "*", num2, "=", num1*num2)
    case "/":
        if num2 == 0 {
            fmt.Println("Cannot divide by zero")
        } else {
            fmt.Println(num1, "/", num2, "=", num1/num2)
        }
    default:
        fmt.Println("Invalid operation")
    }

    // Flush the standard output stream
    fmt.Println("")
}
833 chars
41 lines

This implementation takes two floats and an operation as inputs, and uses a switch statement to perform the requested operation. Note that the division operation checks for a denominator of zero and prints an error message if necessary.

You can run this program by saving it to a file (e.g. calculator.go) and typing go run calculator.go in your terminal.

related categories

gistlibby LogSnag