如何突破Golang中的无限循环 [英] How do I break out of an infinite loop in Golang

查看:58
本文介绍了如何突破Golang中的无限循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用Go语言编写一个程序来猜测一个随机数.我在for循环中遇到问题.

  1. 我无法停止for循环的不断迭代.
  2. 一旦满足条件,我该如何跳出循环.

      for循环== true {//fmt.Println("read number,i,"/n)如果i == ans {fmt.Println(做得好")}如果i!= ans {fmt.Println("Nope")fmt.Scan(i)} 

解决方案

您需要中断:<{fmt.Scan(i)如果i == ans {fmt.Println(做得好")休息}如果i!= ans {fmt.Println("Nope")}}

I'm making a program in Go for guessing a random number. I'm having issues with a for loop.

  1. I can't stop the for loop from continuously iterating.
  2. How do i break out of the loop once a condition is satisfied.

    for loop == true {
    
    //fmt.Println("read number", i, "/n")
    if i == ans {
        fmt.Println("well done")
    }
    if i != ans {
        fmt.Println("Nope")
        fmt.Scan(i)
    }
    

解决方案

You need to break out of the loop:

for {
    fmt.Scan(i)
    if i == ans {
        fmt.Println("well done")
        break
    }
    if i != ans {
        fmt.Println("Nope")
    }
}

这篇关于如何突破Golang中的无限循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆