-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdemo_calc.go
67 lines (61 loc) · 949 Bytes
/
demo_calc.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
56
57
58
59
60
61
62
63
64
65
66
67
package trygo
import (
"bufio"
"fmt"
"os"
"strconv"
)
var reader = bufio.NewReader(os.Stdin)
var st = new(calcstack)
type calcstack struct {
i int
data [10]int
}
func (s *calcstack) push(k int) {
if s.i+1 > 9 {
return
}
s.data[s.i] = k
s.i++
}
func (s *calcstack) pop() (ret int) {
s.i--
if s.i < 0 {
s.i = 0
return
}
ret = s.data[s.i]
return
}
// DemoCalc func
func DemoCalc() {
for {
s, err := reader.ReadString('\n')
var token string
if err != nil {
return
}
for _, c := range s {
switch {
case c >= '0' && c <= '9':
token = token + string(c)
case c == ' ':
r, _ := strconv.Atoi(token)
st.push(r)
token = ""
case c == '+':
fmt.Printf("%d\n", st.pop()+st.pop())
case c == '*':
fmt.Printf("%d\n", st.pop()*st.pop())
case c == '-':
p := st.pop()
q := st.pop()
fmt.Printf("%d\n", q-p)
case c == 'q':
return
default:
//error
}
}
}
}