英文:
Different execution under Windows and Linux with Go
问题
我在Go语言中创建了一个非常简单的猜数字游戏。问题是,在Windows和Linux下执行时会有不同的结果。例如,在Ubuntu上执行时一切正常。但是当我尝试在Windows下启动它时,编译没有问题,但在执行时,当我输入一些内容(例如5)时,它会打印两次"Smaller than random num"或"Bigger than random num"。我不知道为什么会发生这种情况。
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
var number int //声明
var tries int = 0
random_number := random(1, 9) //获取随机数
for {
//fmt.Printf("Enter your prediction: ")
fmt.Scanf("%v", &number)
if number == random_number {
break
} else if number < random_number {
fmt.Printf("Smaller than random num\n")
} else {
fmt.Printf("Bigger than random num\n")
}
tries++
}
fmt.Printf("You guessed correctly in %v tries", tries)
}
func random(min, max int) int {
rand.Seed(time.Now().Unix())
return rand.Intn(max-min) + min
}
以上是你提供的代码的翻译。
英文:
I created a very small game of number guessing in Go. The thing is, it executes differently under Windows and under Linux. By executing it on Ubuntu for example, everything works just fine. But when I try to start it under Windows, it compiles just fine but during execution when I enter something (for example 5) it prints me twice "Smaller than random num"or "Bigger than random num". I have no idea why it happens.
package main
import (
"fmt"
"math/rand"
"time"
)
func main () {
var number int //declaration
var tries int = 0
random_number := random(1, 9) //gets random number
for ; ;tries++ {
//fmt.Printf("Enter your prediction: ")
fmt.Scanf("%v",&number)
if number == random_number {
break;
} else if number<random_number{
fmt.Printf("Smaller than random num\n")
} else {
fmt.Printf("Bigger than random num\n")
}
}
fmt.Printf("You guessed correctly in %v tries",tries)
}
func random(min, max int) int {
rand.Seed(time.Now().Unix())
return rand.Intn(max - min) + min
}
答案1
得分: 2
新行在Linux和Windows中是不同的,因此您的程序的行为也不同。
请参考此问题:https://github.com/golang/go/issues/5391
要解决此问题,您可以将Scanf替换为以下内容(注意末尾的"\n"):
fmt.Scanf("%v\n",&number)
英文:
Newlines are different in Linux and Windows, and thus your program behaves differently.
See this issue: https://github.com/golang/go/issues/5391
To fix this, you can replace your Scanf with this (note the "\n" at the end):
fmt.Scanf("%v\n",&number)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论