DEV Community

the_stranger
the_stranger

Posted on

Command line calculator in GO

This is the code for the Calculator:

package main

import (
    "fmt"
    "math"
)

func main() {

    var num1, num2 float64
    var operator string

    fmt.Println("Welcome to the calculator")

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

    fmt.Print("Enter your operator '+, -, *, /, %, ^' : ")
    fmt.Scanln(&operator)

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

    result := calculate(num1, num2, operator)

    fmt.Printf("Result : %f %s %f = %f\n", num1, operator, num2, result)
    fmt.Println("Thank You for using the calculator :)")
}

func calculate(num1, num2 float64, operator string) float64 {

    var result float64

    switch operator {
        case "+":
            result = num1 + num2
        case "-":
            result = num1 - num2
        case "*":
            result = num1 * num2
        case "%":
            result = (num1 / num2) * 100
        case "^":
            result = math.Pow(num1, num2)
        case "/":
            if num2 != 0 {
                result = num1 / num2
            } else {
                fmt.Println("Divide by Zero '0' error!")
            }
        default:
            fmt.Println("Invalid operator!")
    }

    return result
}
Enter fullscreen mode Exit fullscreen mode

You can run this code by using:
"go run your_file_name.go"

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series

👋 Kindness is contagious

DEV is better (more customized, reading settings like dark mode etc) when you're signed in!

Okay