我們的項(xiàng)目是使用 Go 制作一款實(shí)用的剪刀石頭布游戲。我認(rèn)為這是一個(gè)很好的地方,可以就我可能犯的一些明顯錯(cuò)誤尋求一些指導(dǎo)。我有幾個(gè)問(wèn)題。無(wú)論用戶輸入什么,程序都會(huì)說(shuō)我總是輸入“rock”。無(wú)論我輸入什么,程序總是告訴我這是一個(gè)“平局”所以對(duì)我來(lái)說(shuō)很明顯我的 if/else 語(yǔ)句有問(wèn)題,但我不確定它在哪里以及到底是什么。我也知道我的PlayerPlay功能很丑陋,但由于某種原因,當(dāng)我最初在那里顯示我的顯示菜單時(shí),它會(huì)繼續(xù)循環(huán)回到我的菜單,而不繼續(xù)執(zhí)行程序的其余部分。package mainimport ( "fmt" "math/rand" "time")func ComputerPlay() int { return rand.Intn(2) + 1}func PlayerPlay(play int) int { fmt.Scanln(&play) return play}func PrintPlay(playerName string, play int) { fmt.Printf("%s picked ", playerName) if play == 0 { fmt.Printf("rock\n") } else if play == 1 { fmt.Printf("paper\n") } else if play == 2 { fmt.Printf("scissors\n") } fmt.Printf("Computer has chose ") switch ComputerPlay() { case 0: fmt.Println("rock\n") case 1: fmt.Println("paper\n") case 2: fmt.Println("scissors\n")}}func ShowResult(computerPlay int, humanPlay int){ var play int computerPlay = ComputerPlay() humanPlay = PlayerPlay(play) if humanPlay == 0 && humanPlay == 0 { fmt.Printf("It's a tie\n") } else if humanPlay == 0 && computerPlay == 1 { fmt.Printf(" Rock loses to paper\n") } else if humanPlay == 0 && computerPlay == 2 { fmt.Printf("Rock beats scissors\n") } else if humanPlay == 1 && computerPlay == 0 { fmt.Printf(" Paper beats rock\n") } else if humanPlay == 1 && computerPlay == 1 { fmt.Printf("It's a tie!\n") } else if humanPlay == 1 && computerPlay == 2 { fmt.Printf("Paper loses to scissors\n") } else if humanPlay == 2 && computerPlay == 0 { fmt.Printf("Scissors loses to rock\n") } else if humanPlay == 2 && computerPlay == 1 { fmt.Printf(" Scissors beats paper\n") } else if humanPlay == 2 && computerPlay == 2 { fmt.Printf(" It's a tie!\n") }}
1 回答

躍然一笑
TA貢獻(xiàn)1826條經(jīng)驗(yàn) 獲得超6個(gè)贊
問(wèn)題是您在 PlayerPlay 函數(shù)中使用按值參數(shù)傳遞而不是按引用參數(shù)傳遞。
golang 中的函數(shù)始終按值傳遞(“原始”或指針)。按值傳遞的參數(shù)是不可變的。它將在內(nèi)存中分配新的空間,與
var play
.在您的
PlayerPlay()
函數(shù)中,fmt.Scanln(&play)
嘗試讀取和復(fù)制新分配的空間的值并成功完成,但引用錯(cuò)誤(不在您的var play
)。因此,該
var play
變量將保持默認(rèn)值不變(對(duì)于 int 為 0)。而你最終總是會(huì)做出選擇。
您需要做的是將PlayerPlay()
函數(shù)更改為接受引用類型,并用 的引用填充它,var play
以便fmt.Scanln()
可以改變var play
.
例如。
func PlayerPlay(play *int) { fmt.Scanln(play) }
像這樣使用它們,
var play int PlayerPlay(&play)
請(qǐng)注意,該&
符號(hào)用于獲取值的引用(指針)。
- 1 回答
- 0 關(guān)注
- 155 瀏覽
添加回答
舉報(bào)
0/150
提交
取消