编辑代码

package main

import (
	"fmt"
	"strconv"
	"strings"
)

func main() {
	fmt.Println("请输入一个算术表达式(仅支持两个操作数):")
	var expression string
	fmt.Scan(&expression)

	// 从字符串中解析出操作数和运算符
	operatorIndex := -1
	operators := []string{"+", "-", "*", "/"}
	for _, op := range operators {
		if strings.Contains(expression, op) {
			operatorIndex = strings.Index(expression, op)
			break
		}
	}
	if operatorIndex == -1 {
		fmt.Println("不支持的运算符")
		return
	}

	num1, err := strconv.Atoi(expression[:operatorIndex])
	if err != nil { // 如果输入的不是数字,返回错误提示
		fmt.Println("无效的数字")
		return
	}

	num2, err := strconv.Atoi(expression[operatorIndex+1:])
	if err != nil { // 如果输入的不是数字,返回错误提示
		fmt.Println("无效的数字")
		return
	}

	operator := expression[operatorIndex : operatorIndex+1]
	result := 0

	switch operator {
	case "+":
		result = num1 + num2
	case "-":
		result = num1 - num2
	case "*":
		result = num1 * num2
	case "/":
		result = num1 / num2
	default:
		fmt.Println("无效的运算符")
		return
	}

	fmt.Printf("%d %s %d = %d", num1, operator, num2, result)
}