Golang数组输入不按预期工作

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

Golang array input not working as expected

问题

我写了一段简单的代码来读取 Golang 中的数组:

  1. func main() {
  2. var n int
  3. fmt.Scanf("%d", &n)
  4. var arr [200]int
  5. for i := 0; i < n; i++ {
  6. fmt.Printf("\nEnter %d:", i)
  7. fmt.Scanf("%d", &arr[i])
  8. }
  9. }

它生成以下输出:

  1. go run array_input.go
  2. 5
  3. Enter 0:1
  4. Enter 1:
  5. Enter 2:2
  6. Enter 3:
  7. Enter 4:4

在这里,当我为数组位置 0 输入值时,它会自动跳到数组位置 2,而不会为数组位置 1 输入任何值。我不明白为什么会这样发生。

谢谢。

英文:

I have a written a simple piece of code to read array in golang

  1. func main(){
  2. var n int
  3. fmt.Scanf(&quot;%d&quot;, &amp;n)
  4. var arr [200] int
  5. for i := 0; i &lt; n; i++ {
  6. fmt.Printf(&quot;\nEnter %d:&quot;, i)
  7. fmt.Scanf(&quot;%d&quot;, arr[i])
  8. }
  9. }

It is generating below output:

  1. go run array_input.go
  2. 5
  3. Enter 0:1
  4. Enter 1:
  5. Enter 2:2
  6. Enter 3:
  7. Enter 4:4

Here when I enter value for array location 0, it automatically jumps to array location 2 without taking any value for array location 1. I am not able to understand why it is happening.

Thanks

答案1

得分: 4

你应该在arr[i]之前添加'&'符号。

  1. func main(){
  2. var n int
  3. fmt.Scanf("%d", &n)
  4. var arr [200] int
  5. for i := 0; i < n; i++ {
  6. fmt.Printf("\nEnter %d:", i)
  7. fmt.Scanf("%d", &arr[i])
  8. }
  9. }
英文:

You should add '&' before arr[i]

  1. func main(){
  2. var n int
  3. fmt.Scanf(&quot;%d&quot;, &amp;n)
  4. var arr [200] int
  5. for i := 0; i &lt; n; i++ {
  6. fmt.Printf(&quot;\nEnter %d:&quot;, i)
  7. fmt.Scanf(&quot;%d&quot;, &amp;arr[i])
  8. }
  9. }

huangapple
  • 本文由 发表于 2017年8月2日 12:18:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/45451402.html
匿名

发表评论

匿名网友

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

确定