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

如何在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条)

报告相同问题?

悬赏问题

  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?
  • ¥15 关于#vue.js#的问题:修改用户信息功能图片无法回显,数据库中只存了一张图片(相关搜索:字符串)
  • ¥15 texstudio的问题,