如何在Go中将数字列表读入数组

I want to read a list of numbers given by the user into an array and perform operations on them.

package main
import "fmt"

func main() {
    var n,c,i int
    var a []int    
fmt.Println("Enter the number of inputs")
 fmt.Scanln(&n)
fmt.Println("Enter the inputs")
 for i=0 ; i<n-1; i++ {
     fmt.Scanln(&c)
}
    fmt.Println(a[i]) 
}

Can someone help me out.

What you are using is slices not arrays. Arrays can only be used when you know the length at compile time.

package main

import "fmt"

func main() {
    length := 0
    fmt.Println("Enter the number of inputs")
    fmt.Scanln(&length)
    fmt.Println("Enter the inputs")
    numbers := make([]int, length)
    for i := 0; i < length; i++ {
        fmt.Scanln(&numbers[i])
    }
    fmt.Println(numbers)
}

I noticed several problems with your code:

  • a slice is a more appropriate data structure here since the length of the input is unknown at compile time
  • the value at each input is not saved into the array
  • the variable c could be omitted entirely by inserting into the array directly
  • off-by-one error on the scanning process

I've applied these fixes in the code below:

package main

import "fmt"

func main() {
  var n, i int
  fmt.Println("Enter the number of inputs")
  fmt.Scanln(&n)

  fmt.Println("Enter the inputs")
  a := make([]int, n)
  for i = 0; i < n; i++ {
    fmt.Scanln(&a[i])
  }

  fmt.Println(a)
}