在Windows和Linux下使用Go的执行方式不同。

huangapple go评论90阅读模式
英文:

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 (
	&quot;fmt&quot;
    &quot;math/rand&quot;
    &quot;time&quot;
)

func main () {
	var number int //declaration
	var tries int = 0
	random_number := random(1, 9) //gets random number
    for ; ;tries++ {
	    	    //fmt.Printf(&quot;Enter your prediction: &quot;)
	    	    fmt.Scanf(&quot;%v&quot;,&amp;number)
		    	if number == random_number {
		    			break;
		    	} else if number&lt;random_number{
		    				fmt.Printf(&quot;Smaller than random num\n&quot;)
		    	} else {
		    				fmt.Printf(&quot;Bigger than random num\n&quot;)
		    	}
		 }
    fmt.Printf(&quot;You guessed correctly in %v tries&quot;,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(&quot;%v\n&quot;,&amp;number)

huangapple
  • 本文由 发表于 2017年5月7日 16:55:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/43829627.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定