1. 程式人生 > >1.8 程式運算1:數學運算

1.8 程式運算1:數學運算

加減乘除求餘都是很簡單的數學計算,直接上程式碼

package main

import "fmt"

func main() {
    demo61()
}

func demo61() {
    var ret float32
    //ret = getResult(5, 3, "+")
    //fmt.Println("ret=", ret)
    //ret = getResult(5, 3, "-")
    //fmt.Println("ret=", ret)
    //ret = getResult(5, 3, "*")
    //fmt.Println("ret=", ret)
ret = getResult2(5, 3, "/") fmt.Println("ret=", ret) ret = getResult2(5, 3, "%") fmt.Println("ret=", ret) } //if-elseif-else結構 func getResult(a float32, b float32, operator string) (ret float32) { /* 單分支 if operator=="+"{ ret = a+b } */ /* //雙分支 if operator=="+"{ ret = a+b }else { fmt.Printf("不支援的操作符:%s\n",operator) } */
//多分支 if operator == "+" { ret = a + b } else if operator == "-" { ret = a - b } else if operator == "*" { ret = a * b } else if operator == "/" { ret = a / b } else if operator == "%" { ret = float32(int(a) % int(b)) } else { fmt.Printf("不支援的操作符:%s\n"
, operator) } return } //switch-case-default結構 func getResult2(a float32, b float32, operator string) (ret float32) { //判斷operator的取值 switch operator { //情形1,2,3... case "+": ret = a + b case "-": ret = a - b case "*": ret = a * b case "/": ret = a / b case "%": ret = float32(int(a) % int(b)) //如果不符合上述任何一種情形 default: fmt.Printf("不支援的操作符:%s\n", operator) } return }