Go语言中如何将扫描到的值应用到数组的长度中?

问题描述 投票:0回答:1

我想将扫描的值添加到数组的长度中,但我的代码有错误。 我们不能像其他编程语言那样做到这一点。


    package main
    
    import "fmt"
    
    func main() {
    
    var number_of_student int
    
    fmt.Print("Enter the number of Student: ")
    fmt.Scan(&number_of_student)
    
    var Student_marks[number_of_student] int
    
    for i:=0;i<=number_of_student-1;i++{
    
    fmt.Print("Enter the ",i+1," student mark")
    fmt.Scan(&Student_marks[i])
    }
    }

我希望我可以将扫描的值添加到数组的长度中。终端出现错误;它说“无效的数组长度 number_of_student”。

go
1个回答
0
投票

这会起作用:

var studentCount int

fmt.Print("Enter the number of Student: ")
fmt.Scan(&studentCount)

studentMarks := make([]int, studentCount)

for i := 0; i < len(studentMarks); i++ {
    fmt.Print("Enter the ", i+1, " student mark: ")
    fmt.Scan(&studentMarks[i])
}
© www.soinside.com 2019 - 2024. All rights reserved.