go逆波兰式计算器

编写一个简单的逆波兰式计算器,它接受用户输入的整型数(最大值 999999)和运算符 +、-、*、/。
输入的格式为:number1 ENTER number2 ENTER operator ENTER --> 显示结果

package main

import (
	"bufio"
	"errors"
	"fmt"
	"os"
	"strconv"
	"strings"
)

func main() {
	//for {
	//	fmt.Print("please input some thing(S to quit):")
	//	s := Input()
	//	if strings.ToUpper(s) == "S" {
	//		return
	//	}
	//	fmt.Println(s)
	//}
	for {
		fmt.Print("please input the first number:")
		var a string = Input()
		fmt.Print("please input the second number:")
		var b string = Input()
		fmt.Print("please input the operator:")
		var c string = Input()
		r, err := Calim(a, b, c)
		if err != nil {
			fmt.Println(err)
			continue
		}
		fmt.Println(r)
		fmt.Printf("the reslut is :%s %s %s = %.4f \n", a, c, b, r)

	}

}

func Calim(a, b, c string) (float64, error) {
	var x, y, r float64
	if m, err := strconv.ParseFloat(a, 64); err == nil {
		x = m
	} else {
		return 0, err
	}
	if m, err := strconv.ParseFloat(b, 64); err == nil {
		y = m
	} else {
		return 0, err
	}

	switch c {
	case "+":
		r = x + y
	case "-":
		r = x - y
	case "/":
		r = x / y
	case "*":
		r = x * y
	default:
		return 0, errors.New("this oparetor is not supported!")

	}
	return r, nil
}

func Input() string {
	P := bufio.NewReader(os.Stdin)
	s, _ := P.ReadString('\n')
	return strings.TrimSpace(s)
}

你可能感兴趣的:(Go)