处理Golang中的命令漂移

huangapple go评论64阅读模式
英文:

Handling command drift on golang

问题

当从用户端输入数组数据时,输入n = 5后,a[0]自动被赋值为0,并忽略继续输入a[1]。我在其他机器和replit上尝试过,但似乎只在我的电脑上发生。我还尝试卸载和重新安装golang,但没有解决这个问题。

package main

import (
    "fmt"
)

func main() {
    var a = [100]int{}
    var n int
    fmt.Print("N = ")
    fmt.Scanf("%v", &n)
    for i := 0; i < n; i++ {
        fmt.Printf("a[%v] = ", i)
        fmt.Scanf("%v", &a[i])
    }
    for i := 0; i < n; i++ {
        fmt.Printf("%v ", a[i])
    }
    fmt.Println()
}

处理Golang中的命令漂移

英文:

when entering data for the array from the user side. After entering n = 5 the end a[0] is automatically assigned to 0 and is ignored to continue typing a[1]. I tried on other machines and replit but it seems to only happen on my computer. I also tried uninstalling and reinstalling golang but it didn't fix it

package main

import (
    &quot;fmt&quot;
)

func main() {
    var a = [100]int{}
    var n int
    fmt.Print(&quot;N = &quot;)
    fmt.Scanf(&quot;%v&quot;, &amp;n)
    for i := 0; i &lt; n; i++ {
        fmt.Printf(&quot;a[%v] = &quot;, i)
        fmt.Scanf(&quot;%v&quot;, &amp;a[i])
    }
    for i := 0; i &lt; n; i++ {
        fmt.Printf(&quot;%v &quot;, a[i])
    }
    fmt.Println()
}

处理Golang中的命令漂移

答案1

得分: 1

这将为您解决问题,重要的是在Go语言中进行调试。

var a = make([]int, 100)
var n int = 5
fmt.Print("N = ")
fmt.Scanf("%v \n", &n)
for i := 0; i < n; i++ {
    fmt.Printf("a[%v] = ", i)
    _, err := fmt.Scanf("%v \n", &a[i])
    if err != nil {
        fmt.Println("error", err)
    }
}
for i := 0; i < n; i++ {
    fmt.Printf("%v ", a[i])
}
fmt.Println()

https://pkg.go.dev/fmt#pkg-overview

英文:

This will solve the problem for you, it's important to debug in go language.

  var a = make([]int, 100)
    	var n int = 5
    	fmt.Print(&quot;N = &quot;)
    	fmt.Scanf(&quot;%v \n&quot;, &amp;n)
    	for i := 0; i &lt; n; i++ {
    		fmt.Printf(&quot;a[%v] = &quot;, i)
    		_, err := fmt.Scanf(&quot;%v \n&quot;, &amp;a[i])
    		if err != nil {
    			fmt.Println(&quot;error&quot;, err)
    		}
    	}
    	for i := 0; i &lt; n; i++ {
    		fmt.Printf(&quot;%v &quot;, a[i])
    	}
    	fmt.Println()

https://pkg.go.dev/fmt#pkg-overview

huangapple
  • 本文由 发表于 2022年9月28日 19:26:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/73880603.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定