You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
star/calc/calc.go

50 lines
1.1 KiB
Go

2 years ago
package calc
import (
"b612.me/starlog"
"b612.me/staros"
"errors"
"fmt"
"github.com/spf13/cobra"
"strconv"
"strings"
)
var Cmd = &cobra.Command{
Use: "calc",
Short: "计算器",
Long: "简单的计算器",
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) == 0 {
starlog.Errorln("请至少输入一个算式")
return errors.New("no sentense")
}
var res []string
printRes := func() {
for k, v := range res {
fmt.Println(args[k], "=", v)
}
}
for k, v := range args {
for i := k; i > 0; i-- {
v = strings.ReplaceAll(v, "$"+strconv.Itoa(i), res[i-1])
}
v = strings.ReplaceAll(v, "x", "*")
v = strings.ReplaceAll(v, "X", "*")
v = strings.ReplaceAll(v, "×", "*")
v = strings.ReplaceAll(v, "÷", "*")
v = strings.ReplaceAll(v, "", "(")
v = strings.ReplaceAll(v, "", ")")
c, err := staros.Calc(v)
if err != nil {
printRes()
starlog.Errorf("calc %s Error:%v\n", v, err)
return err
}
res = append(res, strconv.FormatFloat(c, 'f', -1, 64))
}
printRes()
return nil
},
}