Kodewick
開始學 →
小挑戰←→0 / 70

文具店賬單

#055小挑戰l.Cost()約 6 分鐘

賬單上的每一行是一個 Line:名字、單價 Price、數量 Qty。先給 Line 寫方法 Cost(),返回這一行的錢(單價乘數量);再寫 Receipt(lines),用它把整張賬單加起來。空賬單就是 0。

示例
Receipt([]Line{{"pencil", 2, 5}, {"notebook", 8, 1}})→18
Receipt([]Line{})→0
函式func Receipt(lines []Line) int
main.go
package main

type Line struct {
	Name  string
	Price int
	Qty   int
}

func (l Line) Cost() int {
	// 在這裡寫:返回單價乘數量
	return 0
}

func Receipt(lines []Line) int {
	total := 0
	for _, l := range lines {
		// 在這裡寫:把這一行的 Cost() 加進 total
	}
	return total
}
Ctrl + Enter 也能執行
結果

寫好了先點「執行」試試示例,沒問題再點「提交」。