英文:
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 "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.
答案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 "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)
}
答案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("Enter the length of slice: ")
fmt.Scanf( "%d", &eleLen)
arr := make([]int, eleLen)
for i:=0; i<eleLen;i++{
fmt.Scanf("%d", &arr[i])
}
fmt.Println(arr)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论