英文:
I have this type of error while iterate arrary in for loop "panic: runtime error: index out of range"
问题
package main
import (
"fmt"
)
func main() {
var a int
var b int
var ar []int
fmt.Scan(&a)
for i := 1; i < a; i++ {
fmt.Scan(&b)
ar[i] = b
}
fmt.Print("Hello")
for i := a; i > 0; i-- {
b = ar[i]
fmt.Print(b)
}
}
package main
import (
"fmt"
)
func main() {
var a int
var b int
var ar []int
fmt.Scan(&a)
for i := 1; i < a; i++ {
fmt.Scan(&b)
ar[i] = b
}
fmt.Print("Hello")
for i := a; i > 0; i-- {
b = ar[i]
fmt.Print(b)
}
}
英文:
package main
import (
"fmt"
)
func main() {
var a int
var b int
var ar [] int
fmt.Scan(&a)
for i:= 1; i<a; i++ {
fmt.Scan(&b)
ar[i] = b
}
fmt.Print("Hello")
for i:= a; i>0; i-- {
b = ar[i]
fmt.Print(b)
}
}
答案1
得分: 1
修正后的代码,我认为这是你想要的:
package main
import (
"fmt"
)
func main() {
var a int
var b int
fmt.Scan(&a)
// 创建长度为a、容量为a、填充为0的切片
ar := make([]int, a, a)
for i := 0; i < a; i++ {
fmt.Scan(&b)
ar[i] = b
}
fmt.Print("Hello")
for i := a - 1; i >= 0; i-- {
b = ar[i]
fmt.Print(b)
}
}
请注意,我只翻译了代码部分,其他内容不做翻译。
英文:
Corrected code, I think it's what you want
package main
import (
"fmt"
)
func main() {
var a int
var b int
fmt.Scan(&a)
// make slice with len a, cap a, 0 filled
ar := make([]int, a, a)
for i := 0; i < a; i++ {
fmt.Scan(&b)
ar[i] = b
}
fmt.Print("Hello")
for i := a - 1; i >= 0; i-- {
b = ar[i]
fmt.Print(b)
}
}
答案2
得分: 0
对于 i:= 1; i<a; i++ {
fmt.Scan(&b)
ar[i] = b
}
ar
是空的。如果你想添加一些内容,可以使用 ar = append(ar, ...)
或者使用正确大小创建 ar
:ar = make(int[], a)
。然后 ar
将包含多个零值。
英文:
for i:= 1; i<a; i++ {
fmt.Scan(&b)
ar[i] = b
}
ar
is empty. If you want to add something, then use ar = append(ar, ...)
Or create ar
with the correct size: ar = make(int[], a)
. Then ar will contain several zero values.
答案3
得分: 0
2个可能的解决方案。一个是利用数组,另一个是利用切片。
何时使用数组(当您知道数组的确切大小时):
将数组声明为ar := make([]int, a)
,其中a
是数组的大小。
何时使用切片(当您不确定确切大小或可能需要扩展时):
像这样将元素追加到数组中:ar = append(ar, b)
。
英文:
2 possible solution. 1 making use of an array the other making use of a slice
When to use an array (When u know the exact size of your array):
Declare your array as ar := make([]int, a)
this assume size of array is a
When to use slice (When u are not sure of the exact size or it may be expanded):
Append to your array like this: ar = append(ar, b)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论