Let’s write a simple console calculator that performs basic arithmetic operations. First, we give it the numbers with which we want to perform operations using the add <number>
command (we can give several numbers). Then we can use the commands inc
, acc
, sub
, mul
, div
, mod
; to do calculations: we enter the index of the number to work with and then the operator arguments. Show
can be used to display the numbers entered earlier; exit
to exit the program.
Example output:
add 42 13
Operands: 42 13
inc 0 1
[43 13]
mod 1 3
[43 1]
exit
Code:
package main import ( "bufio" "fmt" "os" "strconv" "strings" ) func main() { r := bufio.NewReader(os.Stdin) var numbers []int fmt.Println("Enter nums with 'add' and then use calc commands:") fmt.Println("inc, acc, sub, mul, div, mod, show, exit") for { str, err := r.ReadString('\n') if err != nil { panic(err) } str = strings.TrimSpace(str) if str == "exit" { break } // str to slice; separate each word by " " to get command lines strSlice := strings.Split(str, " ") // command (add, inc, etc) cmd := strSlice[0] // numerical args args := []int{} for _, val := range strSlice[1:] { num, err := strconv.Atoi(val) if err != nil { panic(err) } args = append(args, num) } if cmd == "add" { numbers = append(numbers, args...) fmt.Println("Operands:", strings.Trim(fmt.Sprint(numbers), "[]")) } else if cmd == "show" { fmt.Println("Operands: ", numbers) // operations } else if args[0] >= len(numbers) { fmt.Println("Wrong index") } else if cmd == "inc" { numbers[args[0]]++ fmt.Println(numbers) } else if len(args) < 2 { fmt.Println("Should be 2 args") // fix `add 1 2` -> `acc 1` panic } else { switch cmd { case "acc": numbers[args[0]] += args[1] case "sub": numbers[args[0]] -= args[1] case "mul": numbers[args[0]] *= args[1] case "div": if args[1] == 0 { fmt.Println("Don't divide by 0") } else { numbers[args[0]] /= args[1] } case "mod": numbers[args[0]] %= args[1] default: fmt.Println("Enter valid command") } fmt.Println(numbers) } } }