参考代码
package main import ( "flag" "fmt" "os" ) func main() { // 定义命令行参数 op := flag.String("op", "add", "Operation to perform: add, sub, mul, div") a := flag.Float64("a", 0, "First operand") b := flag.Float64("b", 0, "Second operand") // 解析命令行参数 flag.Parse() // 执行运算 var result float64 switch *op { case "add": result = *a + *b case "sub": result = *a - *b case "mul": result = *a * *b case "div": if *b == 0 { fmt.Println("Error: Division by zero") os.Exit(1) } result = *a / *b default: fmt.Println("Unsupported operation:", *op) os.Exit(1) } // 打印结果 fmt.Printf("Result: %.2f\n", result) }