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 }, }