我正在尝试完成 Exercise: Slices
from the Go Tour .
但是我真的不明白我被要求做什么。
Implement Pic. It should return a slice of length dy, each element of which is a slice of dx 8-bit unsigned integers. When you run the program, it will display your picture, interpreting the integers as grayscale (well, bluescale) values.
我有以下代码
package main
import "golang.org/x/tour/pic"
func Pic(dx, dy int) [][]uint8 {
a := make([][]uint8, dy)
return a
}
func main() {
pic.Show(Pic)
}
到目前为止,我已经创建了长度为 dy 的 slice 。但是我不明白下一步。我是否需要创建一个 for 循环,在其中我将 slice 的每个元素分配给 dx 范围内的值?我不要求代码,而是要求解释/澄清
最佳答案
Do I need to create a for loop in which I assign every element of my slice to a value in the range of dx?
是的:
- 一个外部循环,用于为 [x] 分配一个
[]uint8
大小的dx
slice , - 为每个元素
a[x]
(它是一个[]uint8
)使用内部循环 'y
' 以便分配a[x][y]
与请求值(即“有趣的函数”之一,如x^y
、(x+y)/2
和x*y
)。
x
和y
是 slice 范围内的索引(a
,然后是a[x]
):参见"For
statements "。
我喜欢 (x ^ y) * (x ^ y)
:
x*x + y*y
is another good one
Waqas Ilyas建议 the comments : y * 10000/(x + 1)
关于go - Go 练习之旅 #18 : Slices,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25459474/