第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

為什么我的解決方案對于 go slices 練習不正確?

為什么我的解決方案對于 go slices 練習不正確?

Go
慕慕森 2022-10-10 17:54:03
我正在學習 golang 并試圖完成 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)/2, x*y, and x^y.(You need to use a loop to allocate each []uint8 inside the [][]uint8.)(Use uint8(intValue) to convert between types.)我的解決方案:package mainimport "golang.org/x/tour/pic"func Pic(dx, dy int) [][]uint8 {    ans := make([][]uint8, dy)    for i:=0; i< dy; i++ {        slice := make([]uint8, dx)        for j := 0; j<dx;j++{            slice = append(slice, uint8((i+j)/2))        }        ans = append(ans,slice)    }    return ans}func main() {    pic.Show(Pic)}運行時出現(xiàn)錯誤:恐慌:運行時錯誤:索引超出范圍 [0],長度為 0我不確定我在這里做錯了什么。另外,為什么在練習中傳遞了一個函數(shù)?這是故意的嗎?
查看完整描述

1 回答

?
慕神8447489

TA貢獻1780條經驗 獲得超1個贊

好,我知道了。正如我在評論中所說,您應該用slice[j] = uint((i+j)/2)and替換您的附加調用ans[i] = slice

該練習使用 256x256 調用您的函數(shù)。您創(chuàng)建一個 256 長的切片,然后將其他切片附加 256 次,得到一個 512 長的切片ans。前 256 個條目是空的,因為 appendslice在末尾追加。因此,當 pic 庫迭代您的數(shù)據(jù)時,它會嘗試訪問一個空切片。

更新:修復算法的另一種方法是初始化長度為 0 的切片。所以編輯

ans := make([][]uint8, 0)和 slice := make([]uint8, 0)

也應該給出正確的結果。


查看完整回答
反對 回復 2022-10-10
  • 1 回答
  • 0 關注
  • 144 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號