如何在Go编程中找到对角线差异?

huangapple go评论79阅读模式
英文:

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 &quot;fmt&quot;

func main() {
	var n int
	fmt.Scan(&amp;n)
	s := make([][]int, n)
	for i := 0; i &lt; n; i++ {
		for j := 0; j &lt; n; j++ {
			fmt.Scanf(&quot;%d %d&quot;, &amp;s[i][j])
		}
	}
	s1 := 0
	s2 := 0
	for i := 0; i &lt; n; i++ {
		for j := 0; j &lt; 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 &lt; n; i++ {
	s[i] = make([]int, n) // YOU ARE MISSING THIS LINE
	for j := 0; j &lt; n; j++ {
		fmt.Scanf(&quot;%d %d&quot;, &amp;s[i][j])
	}
}

huangapple
  • 本文由 发表于 2016年4月18日 15:59:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/36688359.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定