39

go指南:切片练习

 4 years ago
source link: https://studygolang.com/articles/20348?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

题目

地址 https://tour.go-zh.org/moretypes/18

练习:切片

实现 Pic。它应当返回一个长度为 dy 的切片,其中每个元素是一个长度为 dx,元素类型为 uint8 的切片。当你运行此程序时,它会将每个整数解释为灰度值(好吧,其实是蓝度值)并显示它所对应的图像。

图像的选择由你来定。几个有趣的函数包括 (x+y)/2, x y, x^y, x log(y) 和 x%(y+1)。

(提示:需要使用循环来分配 [][]uint8 中的每个 []uint8;请使用 uint8(intValue) 在类型之间转换;你可能会用到 math 包中的函数。)

分析

1.数组大小因为是不定的,所以要用make,二维数组,要使用两次make函数。

2.本地IDE,golang.org/x/tour/pic的下载,需要配置代理。否则下载不下来。

3.int和float类型不能直接相乘。

4.这里用回调会方便很多。

代码

(x+y)/2

package main

import "golang.org/x/tour/pic"

func Pic(dx, dy int) [][]uint8 {
    var pic [][]uint8

    pic = make([][]uint8, dx)

    for i := 0; i < dx; i++ {
        pic[i] = make([]uint8, dy)
        for j := 0; j < dy; j++ {
            pic[i][j] = uint8((i + j) /2)  //每次改变这里
        }
    }
    
    return pic;
}

func main() {
    pic.Show(Pic)

}
EvE3Y3i.png!web

image.png

x*y

pic[i][j] = uint8(i*j)
n6RbEj2.png!web

image.png

x^y

pic[i][j] = uint8(math.Pow(float64(i),float64(j)))
bqaaaaR.png!web

image.png

x*log(y)

pic[i][j] = uint8(float64(i) * (math.Log(float64(j))))
MRZvYbR.png!web

image.png

x%(y+1)

pic[i][j] = uint8(i%(j+1))
Fbuaaaf.png!web

image.png


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK