-
Notifications
You must be signed in to change notification settings - Fork 64
Expand file tree
/
Copy pathexample_calculator_test.go
More file actions
46 lines (44 loc) · 916 Bytes
/
example_calculator_test.go
File metadata and controls
46 lines (44 loc) · 916 Bytes
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
package decimal
import (
"fmt"
"os"
"strings"
)
func ExampleBig_reversePolishNotationCalculator() {
ctx := Context128
const input = "15 7 1 1 + - / 3 * 2 1 1 + + - 5 * 3 / ="
var stack []*Big
Loop:
for _, tok := range strings.Split(input, " ") {
last := len(stack) - 1
switch tok {
case "+":
x := stack[last-1]
ctx.Add(x, x, stack[last])
stack = stack[:last]
case "-":
x := stack[last-1]
ctx.Sub(x, x, stack[last])
stack = stack[:last]
case "/":
x := stack[last-1]
ctx.Quo(x, x, stack[last])
stack = stack[:last]
case "*":
x := stack[last-1]
ctx.Mul(x, x, stack[last])
stack = stack[:last]
case "=":
break Loop
default:
var x Big
if _, ok := x.SetString(tok); !ok {
fmt.Fprintf(os.Stderr, "invalid decimal: %v\n", x.Context.Err())
os.Exit(1)
}
stack = append(stack, &x)
}
}
fmt.Printf("%+6.4g\n", stack[0])
// Output: +8.333
}