gpt4 book ai didi

在 linux 上正确运行程序,但在 windows 上不能

转载 作者:IT王子 更新时间:2023-10-29 01:37:54 25 4
gpt4 key购买 nike

我目前正在学习 Go 语言。在不同平台上尝试:Linux、Windows当我在 Linux 上运行代码时它运行完美,但是当我在 Windows 上尝试这个程序时它不起作用。

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

什么不起作用:

  1. 解析整数
  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

是我做错了什么还是不是我的错?

最佳答案

感谢@zerkms 的帮助。

答案是:

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

现在它可以在 windows 和 linux 上正常工作了

关于在 linux 上正确运行程序,但在 windows 上不能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53233415/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com