dongxieyi9115
2012-12-22 04:33
浏览 253
已采纳

如何在Go中使用fmt.Scanf

I seem to be having a queer problem while getting user input within a for loop in go. Here is my code

package main

import "fmt"

func main() {
    var num int
    for i := 0; i < 10; i++ {
        fmt.Printf("Debug: i : %d ", i)
        fmt.Scanf("%d", &num)
        fmt.Println(num)
    }
}

What happens when I run this code is this :

Debug: i : 0
Enter next number
1
1
Debug: i : 1
Enter next number
1
Debug: i : 2
Enter next number
2
2
Debug: i : 3
Enter next number
2
Debug: i : 4
Enter next number
3
3
Debug: i : 5
Enter next number
3
Debug: i : 6
Enter next number
4
4
Debug: i : 7
Enter next number
4
Debug: i : 8
Enter next number
5
5
Debug: i : 9
Enter next number
5

What I notice is that each iteration of the loop happens twice, Could this be because Go is using parallelism by default and causing both processors to run the code within a for loop?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • dongzhang4301 2012-12-22 07:35
    已采纳

    What OS are you using? Windows?

    Try this:

    package main
    
    import "fmt"
    
    func main() {
        var num int
        for i := 0; i < 10; i++ {
            fmt.Printf("Debug: i : %d
    ", i)
            fmt.Println("Enter next number")
            n, err := fmt.Scanf("%d
    ", &num)
            if err != nil {
                fmt.Println(n, err)
            }
            fmt.Println(num)
        }
    }
    

    Output:

    Debug: i : 0
    Enter next number
    1
    1
    Debug: i : 1
    Enter next number
    2
    2
    Debug: i : 2
    Enter next number
    3
    3
    Debug: i : 3
    Enter next number
    4
    4
    Debug: i : 4
    Enter next number
    5
    5
    Debug: i : 5
    Enter next number
    6
    6
    Debug: i : 6
    Enter next number
    7
    7
    Debug: i : 7
    Enter next number
    8
    8
    Debug: i : 8
    Enter next number
    9
    9
    Debug: i : 9
    Enter next number
    10
    10
    
    评论
    解决 无用
    打赏 举报
查看更多回答(2条)

相关推荐 更多相似问题