为什么变量不在 for 循环内更新?

时间:2021-01-17 21:49:21

标签: go variables scope

我遇到了一个我不明白的问题,func main 中有一个变量没有在 for 循环内更新,我真的不明白为什么变量没有收到新值。这是一个编码游戏练习。每次内循环完成时,我都必须获得最高的山峰然后拍摄它,我实现的逻辑很好,但我只需要更新可变的拍摄点,因此每次迭代都会拍摄山峰,但我总是收到初始值取而代之的是 0。请注意,我不是在寻找练习的答案,而是在寻找问题的解决方案。 这里是游戏 -> https://www.codingame.com/ide/puzzle/the-descent

代码如下:

    func main() {
    shoot := 0   //this is the variable I want to be updated
    higherMountainH := 0
    for {

        for i := 0; i < 8; i++ {

            var mountainH int  // This variable is updated in each iteration by game giving the hight of the mountain so it always returns a variable from 9 to 2

            if mountainH > higherMountainH { //mountainH is never 0 because the game engine gives to it the corresponding value in each iteration
                higherMountainH = mountainH
                shoot = i   //Here is where it is supposed to be updated
            }

            fmt.Scan(&mountainH)
        }
        
        fmt.Println(shoot)  //here always receive 0
        higherMountainH = 0  
        shoot = 0
    }
 }

1 个答案:

答案 0 :(得分:-1)

问题在于每次迭代都会覆盖 mountainH

for i := 0; i < 8; i++ {
    // Here mountainH is created and is set to 0 at every iteration.
    var mountainH int
    // So the condition is always false.
    if mountainH > higherMountainH {
        higherMountainH = mountainH
        shoot = i
    }
    // mountainH is read after the condition is checked.
    fmt.Scan(&mountainH)
}

固定版本:

// If you define the variable outside of the loop it won't be 
// overwritten at every iteration.
var mountainH int
for i := 0; i < 8; i++ {
    if mountainH > higherMountainH {
        higherMountainH = mountainH
        shoot = i
    }
    fmt.Scan(&mountainH)
}
相关问题