duanbeng1923 2019-09-07 08:48
浏览 78
已采纳

输入小于9时如何停止Go循环?

var (
        value1, value2 float64
    )
for value1 < 9 || value2 < 9 || value1 < 9 && value2 < 9 {
    fmt.Print("Masukan berat belanjaan di dalam kantong : ")
    fmt.Scan(&value1, &value2)
}

fmt.Println("Program Selesai")

I want the program does looping to show inputs from the user and stop when one of the two inputs is less than 9. But the program always stops when both of value is more than or equals 9. Help me to fix it.

  • 写回答

3条回答 默认 最新

  • du16178 2019-09-07 09:31
    关注

    I recommend using a function:

    func input(value *float64) bool {
        fmt.Print("Enter the weight of the grocery in the bag (less than 9 ends the loop):")
        _, err := fmt.Scan(value)
        if err != nil {
            log.Fatal(err)
        }
        fmt.Println("You entered:", *value)
        return *value >= 9.0
    }
    

    Which makes your main loop very clean:

        for input(&value1) && input(&value2) {
        }
    

    You may try this:

    package main
    
    import (
        "fmt"
        "log"
    )
    
    func main() {
        value1, value2 := 0.0, 0.0
        for input(&value1) && input(&value2) {
        }
        fmt.Println("Done.")
    }
    
    func input(value *float64) bool {
        fmt.Print("Enter the weight of the grocery in the bag (less than 9 ends the loop):")
        _, err := fmt.Scan(value)
        if err != nil {
            log.Fatal(err)
        }
        fmt.Println("You entered:", *value)
        return *value >= 9.0
    }
    

    Output:

    Enter the weight of the grocery in the bag (less than 9 ends the loop):12
    You entered: 12
    Enter the weight of the grocery in the bag (less than 9 ends the loop):7
    You entered: 7
    Done.
    

    You may initialize values to a number like 9.0 or greater, so you don't need to use the break:

        value1, value2 := 9.0, 9.0
        for value1 >= 9 && value2 >= 9 {
            fmt.Print("Masukan berat belanjaan di dalam kantong : ")
            fmt.Scan(&value1, &value2)
        }
    

    And check for errors, e.g.:

            if _, err := fmt.Scan(&value1, &value2); err != nil {
                panic(err)
            }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 如何实验stm32主通道和互补通道独立输出
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题