How to read a list of numbers into an Array in Go

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

How to read a list of numbers into an Array in Go

问题

我想读取用户输入的数字列表并将其存储到数组中,然后对它们进行操作。

package main
import "fmt"

func main() {
    var n, c, i int
    var a []int
    fmt.Println("请输入输入的数量")
    fmt.Scanln(&n)
    fmt.Println("请输入输入")
    for i = 0; i < n-1; i++ {
        fmt.Scanln(&c)
        a = append(a, c)
    }
    fmt.Println(a[i])
}

有人可以帮我吗?

英文:

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

package main
import &quot;fmt&quot;

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

Can someone help me out.

答案1

得分: 6

你正在使用的是切片(slices),而不是数组(arrays)。只有在编译时知道长度的情况下才能使用数组。

package main

import "fmt"

func main() {
    length := 0
    fmt.Println("输入输入的数量")
    fmt.Scanln(&length)
    fmt.Println("输入输入")
    numbers := make([]int, length)
    for i := 0; i < length; i++ {
        fmt.Scanln(&numbers[i])
    }
    fmt.Println(numbers)
}
英文:

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

package main

import &quot;fmt&quot;

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

答案2

得分: 0

slice的输入可以从标准输入中读取,如下所示:

func main() {
    var eleLen int
    fmt.Println("输入切片的长度:")
    fmt.Scanf("%d", &eleLen)

    arr := make([]int, eleLen)
    for i := 0; i < eleLen; i++ {
        fmt.Scanf("%d", &arr[i])
    }
    fmt.Println(arr)
}
英文:

The input of slice can be read from stdin as below,

func main(){
	var eleLen int
	fmt.Println(&quot;Enter the length of slice: &quot;)
	fmt.Scanf( &quot;%d&quot;, &amp;eleLen)

	arr := make([]int, eleLen)
	for i:=0; i&lt;eleLen;i++{
		fmt.Scanf(&quot;%d&quot;, &amp;arr[i])
	}
	fmt.Println(arr)
}

huangapple
  • 本文由 发表于 2017年1月16日 13:14:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/41669840.html
匿名

发表评论

匿名网友

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

确定