【问题标题】:Infinite loop in GoGo中的无限循环
【发布时间】:2020-07-23 00:41:22
【问题描述】:

我想让“for 循环”循环 3 次或直到用户输入除整数以外的其他内容。下面是我的代码,尽管它运行了无数次并打印出用户输入的第一个值。

package main

import "fmt"
import "bufio"
import "strconv"
import "os"
import "sort"

func main(){
    emptySlice := make([]int, 3) // Capacity of 3
    fmt.Println(cap(emptySlice))
    scanner := bufio.NewScanner(os.Stdin) // Creating scanner object
    fmt.Printf("Please enter a number: ")
    scanner.Scan() // Will always scan in a string regardless if its a number

    for i := 0; i < cap(emptySlice); i++ { // Should this not run 3 times?
            input, err := strconv.ParseInt(scanner.Text(), 10, 16)
                    if err != nil{
                        fmt.Println("Not a valid entry! Ending program")
                        break
                    }
                emptySlice = append(emptySlice, int(input)) // adds input to the slice
                sort.Ints(emptySlice) // sorts the slice
                fmt.Println(emptySlice) // Prints the slice
    }   
    
}

【问题讨论】:

标签: for-loop go infinite-loop


【解决方案1】:

我认为有几个小错误,但这个版本应该可以正常工作:

package main

import "fmt"
import "bufio"
import "strconv"
import "os"
import "sort"

func main() {
    emptySlice := make([]int, 3) // Capacity of 3
    fmt.Println(cap(emptySlice))
    scanner := bufio.NewScanner(os.Stdin) // Creating scanner object

    for i := 0; i < cap(emptySlice); i++ { // Should this not run 3 times?
        fmt.Printf("Please enter a number: ")
        scanner.Scan() // Will always scan in a string regardless if its a number

        input, err := strconv.ParseInt(scanner.Text(), 10, 16)
        if err != nil {
            fmt.Println("Not a valid entry! Ending program")
            break
        }
        // emptySlice = append(emptySlice, int(input)) // adds input to the slice
        emptySlice[i] = int(input)
    }

    sort.Ints(emptySlice)   // sorts the slice
    fmt.Println(emptySlice) // Prints the slice

}

我已将提示移到循环中,并且已将 append 调用替换为对先前分配的切片条目的直接分配。否则调用 append 只会增加切片的大小。

我已将排序和打印移到循环之外,因为它们似乎也被错误地放置了。

【讨论】:

  • 我很想向我的反对者(或其他任何明显的人)学习如何更好地回答这个问题。谢谢!
  • 我认为“这个问题真的很糟糕,不应该首先回答。”
【解决方案2】:

问题中的程序以 cap(emptySlice) == 3 开头。鉴于循环的每次完整迭代都会将一个新值附加到空切片,我们知道 cap(emptySlice) >= 3 + i。因此循环不会终止。

我的家庭作业略有不同:最多读取三个整数并按排序顺序打印它们。我是这样做的:

func main() {
    var result []int
    scanner := bufio.NewScanner(os.Stdin)
    for i := 0; i < 3; i++ {
        fmt.Printf("Please enter a number: ")
        if !scanner.Scan() {
            // Exit on EOF or other errors.
            break
        }

        n, err := strconv.Atoi(scanner.Text())
        if err != nil {
            // Exit on bad input.
            fmt.Println(err)
            break
        }
        result = append(result, n)
    }

    sort.Ints(result)
    fmt.Println(result)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-24
    • 1970-01-01
    • 2013-02-22
    • 2011-11-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多