英文:
How to find out diagonal difference in go programming?
问题
我的代码:
package main
import "fmt"
func main() {
var n int
fmt.Scan(&n)
s := make([][]int, n)
for i := 0; i < n; i++ {
s[i] = make([]int, n) // 添加这一行代码
for j := 0; j < n; j++ {
fmt.Scanf("%d %d", &s[i][j])
}
}
s1 := 0
s2 := 0
for i := 0; i < n; i++ {
for j := 0; j < n; j++ {
if i == j {
s1 += s[i][j]
}
if i+j == n-1 {
s2 += s[i][j]
}
}
}
fmt.Println(s1 - s2) // 将这行代码移出循环
}
输出:
panic: runtime error: index out of range
我尝试了一下,但是出现了错误。我想知道这个问题的正确解决方法。
英文:
My code:
package main
import "fmt"
func main() {
var n int
fmt.Scan(&n)
s := make([][]int, n)
for i := 0; i < n; i++ {
for j := 0; j < n; j++ {
fmt.Scanf("%d %d", &s[i][j])
}
}
s1 := 0
s2 := 0
for i := 0; i < n; i++ {
for j := 0; j < n; j++ {
if i == j {
s1 += s[i][j]
}
if i+j == n-1 {
s2 += s[i][j]
}
}
fmt.Println(s1 - s2)
}
}
Output:
panic: runtime error: index out of range
I tried but get panic. I want to know proper solution to this problem.
答案1
得分: 1
这行代码:
s := make([][]int, n)
创建了一个切片的切片,即元素类型为[]int
的切片。它创建了一个包含n
个元素的切片,但是外部切片的元素被初始化为元素类型的零值,而[]int
类型的零值是nil
(就像任何切片类型一样)。
你会得到index out of range
的恐慌,因为外部切片s
的任何元素都具有零长度(因为它们没有被初始化为非nil
切片),所以对于任何j
值,s[i][j]
都会引发恐慌。
如果你想给“内部”切片分配元素,你还需要初始化它们:
for i := 0; i < n; i++ {
s[i] = make([]int, n) // 你漏掉了这一行
for j := 0; j < n; j++ {
fmt.Scanf("%d %d", &s[i][j])
}
}
英文:
This line:
s := make([][]int, n)
Creates a slice of slices, a slice whose elements are of type []int
. It creates a slice with n
elements, but the elements of the outer slice are initialized with the zero value of the element type, and zero value of type []int
is nil
(just like for any slice type).
You get index out of range
panic because any element of the outer slice s
has zero length (because they are not initialized to a non-nil
slice), so s[i][j]
panics for any j
value.
If you want to assign elements to the "inner" slices, you also have to initialize them:
for i := 0; i < n; i++ {
s[i] = make([]int, n) // YOU ARE MISSING THIS LINE
for j := 0; j < n; j++ {
fmt.Scanf("%d %d", &s[i][j])
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论