可以在Linux上正常运行程序,但不能在Windows上运行

时间:2018-11-09 21:20:32

标签: go

我目前正在学习Go lang。在不同的平台上尝试:Linux,Windows 当我在Linux上运行代码时,它可以完美运行,但是当我在Windows上尝试该程序时,它不起作用。

它只是简单的cmd计算器,它允许简单的操作,例如加数,乘以它不处理错误输入,如字符。这是我第一个采用Go语法的程序

什么不起作用:

  1. 解析int
  2. 比较输入

代码:

package main

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

func main() {

    reader := bufio.NewReader(os.Stdin)
    var operation int
    var firstNumber float64
    var secondNumber float64

    fmt.Println("Simple cmd calculator")

    repeat := true

    for repeat {

        fmt.Println("Enter number 1: ")
        firstNumber = getNumber(*reader)

        fmt.Println("Enter number 2: ")
        secondNumber = getNumber(*reader)

        fmt.Println()

        selectOperation(*reader, &operation)

        fmt.Print("You result is: ")

        switch operation {
        case 1:
            fmt.Println(add(firstNumber, secondNumber))
        case 2:
            fmt.Println(subtract(firstNumber, secondNumber))
        case 3:
            fmt.Println(multiply(firstNumber, secondNumber))
        case 4:
            fmt.Println(divide(firstNumber, secondNumber))
        }

        fmt.Println("Do you want to continue? [Y/n]")
        input, _ := reader.ReadString('\n')

        input = strings.Replace(input, "\n", "", -1)

        if !(input == "Y" || input == "y") {
            repeat = false
        }

    }

}

func selectOperation(reader bufio.Reader, operation *int) {
    fmt.Println("1. Add")
    fmt.Println("2. Subtract")
    fmt.Println("3. Multiply")
    fmt.Println("4. Divide")

    fmt.Print("Select operation: ")
    input, _ := reader.ReadString('\n')
    input = strings.Replace(input, "\n", "", -1)
    number, _ := strconv.Atoi(input)
    *operation = number
}

func getNumber(reader bufio.Reader) float64 {

    input, _ := reader.ReadString('\n')
    input = strings.Replace(input, "\n", "", -1)
    convertedNumber, _ := strconv.ParseFloat(input, 64)
    return convertedNumber

}

func add(a float64, b float64) float64 {
    return (math.Round((a+b)*100) / 100)
}

func subtract(a float64, b float64) float64 {
    return (math.Round((a-b)*100) / 100)
}

func multiply(a float64, b float64) float64 {
    return (math.Round(a*b*100) / 100)
}

func divide(a float64, b float64) float64 {
    return (math.Round(a/b*100) / 100)
}

结果:

Linux

Windows

我做错了还是不错?

1 个答案:

答案 0 :(得分:3)

感谢@zerkms的帮助。

答案是

input = strings.Replace(input, "\r", "", -1)
input = strings.Replace(input, "\n", "", -1)

现在它可以在Windows和Linux上正常工作