参考代码

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

  

posted @ 2024-12-18 15:42  飞雪飘鸿  阅读(2)  评论(0编辑  收藏  举报
https://damo.alibaba.com/ https://tianchi.aliyun.com/course?spm=5176.21206777.J_3941670930.5.87dc17c9BZNvLL