forked from unknwon/the-way-to-go_ZH_CN
-
Notifications
You must be signed in to change notification settings - Fork 0
/
calculator.go
executable file
·55 lines (50 loc) · 1.33 KB
/
calculator.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// calculator.go
// example: calculate 3 + 4 = 7 as input: 3 ENTER 4 ENTER + ENTER --> result = 7,
package main
import (
"./stack/stack"
"bufio"
"fmt"
"os"
"strconv"
)
func main() {
buf := bufio.NewReader(os.Stdin)
calc1 := new(stack.Stack)
fmt.Println("Give a number, an operator (+, -, *, /), or q to stop:")
for {
token, err := buf.ReadString('\n')
if err != nil {
fmt.Println("Input error !")
os.Exit(1)
}
token = token[0 : len(token)-2] // remove "\r\n"
// fmt.Printf("--%s--\n",token) // debug statement
switch {
case token == "q": // stop als invoer = "q"
fmt.Println("Calculator stopped")
return
case token >= "0" && token <= "999999":
i, _ := strconv.Atoi(token)
calc1.Push(i)
case token == "+":
q, _ := calc1.Pop()
p, _ := calc1.Pop()
fmt.Printf("The result of %d %s %d = %d\n", p, token, q, p.(int)+q.(int))
case token == "-":
q, _ := calc1.Pop()
p, _ := calc1.Pop()
fmt.Printf("The result of %d %s %d = %d\n", p, token, q, p.(int)-q.(int))
case token == "*":
q, _ := calc1.Pop()
p, _ := calc1.Pop()
fmt.Printf("The result of %d %s %d = %d\n", p, token, q, p.(int)*q.(int))
case token == "/":
q, _ := calc1.Pop()
p, _ := calc1.Pop()
fmt.Printf("The result of %d %s %d = %d\n", p, token, q, p.(int)/q.(int))
default:
fmt.Println("No valid input")
}
}
}