Go语言中如何将扫描值用作数组长度?代码报错解决
在Go中使用动态输入值作为集合长度的解决方案
Go语言里数组的长度必须是编译期就能确定的常量,你用运行时通过fmt.Scan获取的变量number_of_student作为数组长度,这违反了Go的语法规则,所以会抛出"invalid array length number_of_student"错误。
要实现动态长度的集合需求,你需要用**切片(slice)**代替数组。切片可以在运行时动态指定长度,通过make函数创建即可。修改后的代码如下:
package main import "fmt" func main() { var number_of_student int fmt.Print("Enter the number of Student: ") fmt.Scan(&number_of_student) // 用make创建指定长度的切片,替代固定长度的数组 Student_marks := make([]int, number_of_student) for i := 0; i < number_of_student; i++ { fmt.Printf("Enter the %d student mark: ", i+1) fmt.Scan(&Student_marks[i]) } // 可选:打印输入的成绩验证结果 fmt.Println("\nStudent marks entered:") for idx, mark := range Student_marks { fmt.Printf("Student %d: %d\n", idx+1, mark) } }
关键修改说明
- 替换数组声明:把
var Student_marks [number_of_student]int改成Student_marks := make([]int, number_of_student),make函数会在运行时根据输入的数值创建对应长度的切片。 - 简化循环条件:将
i <= number_of_student-1改为i < number_of_student,逻辑更清晰易懂。 - 新增验证逻辑:添加了成绩打印代码,方便确认输入是否正确。
内容的提问来源于stack exchange,提问作者chirath hettiarachchi
相关产品推荐
相关产品推荐

