• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

ATourofGo:Exercise:Slices

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

A Tour of Go系列。如有问题欢迎指出~



第三篇,先解释一下要求:

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.

The choice of image is up to you. Interesting functions include x^y,(x+y)/2, and x*y.

(You need to use a loop to allocate each []uint8 inside the [][]uint8.)

(Use uint8(intValue) to convert between types.)

意思是实现函数Pic,其功能是根据所给的dx,dy做为矩阵的横纵长度,创建一个图像矩阵,矩阵中的值类型为uint8,代表每个像素的灰度值(或者蓝度值)。

下面是代码:

 1 package main
 2 
 3 import "code.google.com/p/go-tour/pic"
 4 
 5 func Pic(dx, dy int) [][]uint8 {
 6     mat := make([][]uint8, dy)
 7     for i := 0; i < dy; i++ {
 8         mat[i] = make([]uint8, dx)
 9     }
10 
11     //draw
12     for y, _ := range mat {
13         for x, _ := range mat[y] {
14             mat[y][x] = uint8(x ^ y)
15         }
16     }
17     return mat
18 }
19 
20 func main() {
21     pic.Show(Pic)
22 }

运行后将输出如下图形:

注意:

  • 矩阵mat的横轴长dx,纵轴长dy。
  • 创建矩阵:make([]Type,len),或者make([]Type,len,cap)。用第二种时请小心,如果指定len(slice长度)为0,cap(slice容量)为大于零的数,该slice中的元素是不能直接引用的(赋值、读取等),所以推荐第一种创建方法。(其他创建方法和slice的len和cap的区别请详见官方文档)
  • 注释//draw下面的代码为绘制矩阵的代码。注意int到uint8的转换,当运行时进行下行转换时,runtime会进行静默处理,如截断等。当进行常量的转换时(如:uint8(1000)),会报错。
  • "^"运算符为二进制XOR(异或)运算。

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
go安装发布时间:2022-07-10
下一篇:
[hdu-6808]GoRunning最小点覆盖网络流2020多校4发布时间:2022-07-10
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap