NASutils Knowledge BaseUnofficialPolski

Go · lesson 21 of 30 · Files and errors · bonusBuild a calculator

A function returns a result or an error; main reads the lines and prints what came back.

Programming on the NAS › Go in 30 lessons

21-calculator.go Download 21-calculator.go

package main

import (
	"bufio"
	"errors"
	"fmt"
	"os"
	"strconv"
	"strings"
)

func calculate(line string) (float64, error) {
	part := strings.Fields(line)
	if len(part) != 3 {
		return 0, errors.New("type number, sign, number with spaces")
	}
	a, errA := strconv.ParseFloat(part[0], 64)
	b, errB := strconv.ParseFloat(part[2], 64)
	if errA != nil || errB != nil {
		return 0, errors.New("one of the numbers is not a number")
	}
	switch part[1] {
	case "+":
		return a + b, nil
	case "-":
		return a - b, nil
	case "*":
		return a * b, nil
	case "/":
		if b == 0 {
			return 0, errors.New("you cannot divide by zero")
		}
		return a / b, nil
	}
	return 0, errors.New("signs: + - * /")
}

func main() {
	fmt.Println("Type a sum like 12 * 4. An empty line ends.")
	in := bufio.NewScanner(os.Stdin)
	for fmt.Print("> "); in.Scan() && in.Text() != ""; fmt.Print("> ") {
		if result, err := calculate(in.Text()); err != nil {
			fmt.Println(err)
		} else {
			fmt.Println(result)
		}
	}
	fmt.Println("Bye")
}

Terminal

$ ./21-calculator
Type a sum like 12 * 4. An empty line ends.
> 12 * 4
48
> 7 / 2
3.5
> 5 / 0
you cannot divide by zero
> five * 2
one of the numbers is not a number
> 
Bye

Exercise

Add ^ with math.Pow.

TurboShell does not contain Go. These programs are made in Bucket & Code with its Go runtime; the finished file runs on the NAS without Go.