-
Notifications
You must be signed in to change notification settings - Fork 0
/
cmdcalc.go
80 lines (73 loc) · 1.57 KB
/
cmdcalc.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
68
69
70
71
72
73
74
75
76
77
78
79
80
package main
import (
"bufio"
"errors"
"fmt"
"os"
"strconv"
"strings"
)
// parseArgs() : validate Arguments by parsing as number
func parseArgs(c []string) (float64, float64, error) {
num1, err := strconv.ParseFloat(c[0], 64)
if err != nil {
return 0.0, 0.0, err
}
num2, err := strconv.ParseFloat(c[2], 64)
if err != nil {
return 0.0, 0.0, err
}
return num1, num2, nil
}
// processStack() : processes the string expression
func processStack(e string) (float64, error) {
result := 0.0
// fmt.Printf("Passed Arg: %#v, Len: %d\n", e, len(e))
c := strings.Split(e, " ")
// fmt.Println("Arg:", e, " len:", len(c))
if len(c)-1 < 2 {
return 0.0, errors.New("error: missing arguments (pass space between number and symbols)")
}
for len(c) > 2 {
num1, num2, err := parseArgs(c)
if err != nil {
return 0.0, err
}
// fmt.Println("num1:", num1, " num2:", num2)
switch c[1] {
case "*":
result = num1 * num2
case "/":
if num2 == 0.0 {
return 0.0, errors.New("error: you tried to divide by zero.")
}
result = num1 / num2
case "+":
result = num1 + num2
case "-":
result = num1 - num2
default:
return 0.0, errors.New("error: operator not from ( + - * / )")
}
res := fmt.Sprintf("%f", result)
c[2] = res
c = c[2:]
}
return result, nil
}
func main() {
for {
scanner := bufio.NewScanner(os.Stdin)
fmt.Print("calc>")
for scanner.Scan() {
// fmt.Println("exp:", scanner.Text())
res, err := processStack(scanner.Text())
if err != nil {
fmt.Println(err)
} else {
fmt.Println(res)
}
fmt.Print("calc>")
}
}
}