Golang中for循环编码任务问题如何解决

Golang中for循环编码任务问题如何解决 我正在构建一个(非常)小的杂货店作为课堂作业。我试图弄清楚如果按下7键,如何跳出我构建的这个循环。当我运行它(在GitHub上)时,如果输入7,它不会跳出循环。知道为什么吗?提前感谢。 (注:所有变量都已创建,cinreader存在,循环可以运行,我只是无法跳出循环)

userInput = reader.ReadIntegerRange(1, 7)
for userInput != 7 {
if userInput == 1 {
subtotal += bananas
} else if userInput == 2 {
subtotal += chicken
} else if userInput == 3 {
subtotal += eggs
} else if userInput == 4 {
subtotal += proteinBars
} else if userInput == 5 {
subtotal += oatmeal
} else if userInput == 6 {
subtotal += blueBerries
} else{
break
}

更多关于Golang中for循环编码任务问题如何解决的实战教程也可以访问 https://www.itying.com/category-94-b0.html

2 回复

检查 ReadIntegerRange 是否包含上限。你也可以使用 fmt.Println(userInput) 来查看在 for 循环内部以及进入嵌套的 if 语句之前正在处理哪个数字……另外(也许你会在课程后面学到)使用 switch 语句可以使你的代码更具可读性和简洁性。

func main() {
    fmt.Println("hello world")
}

更多关于Golang中for循环编码任务问题如何解决的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


你的代码中有一个逻辑问题:userInput 只在循环开始前读取了一次,循环内部没有更新 userInput 的值。因此,即使输入了 7,循环条件 userInput != 7 在第一次迭代后就不会再被重新评估,导致无法跳出循环。你需要在循环内部每次迭代后重新读取用户输入。

以下是修正后的代码示例:

for {
    userInput = reader.ReadIntegerRange(1, 7)
    if userInput == 7 {
        break
    }
    if userInput == 1 {
        subtotal += bananas
    } else if userInput == 2 {
        subtotal += chicken
    } else if userInput == 3 {
        subtotal += eggs
    } else if userInput == 4 {
        subtotal += proteinBars
    } else if userInput == 5 {
        subtotal += oatmeal
    } else if userInput == 6 {
        subtotal += blueBerries
    }
}

在这个修正版本中,使用了一个无限循环 for {},并在每次迭代开始时读取 userInput。如果 userInput 等于 7,立即执行 break 跳出循环;否则,根据输入值更新 subtotal。这样就能确保每次循环都能检查最新的用户输入。

回到顶部