Menu
CoddyTech

回顾:动态列表

本课属于 Coddy GO 学习旅程的“基础知识”单元。第 83 课,共 109 课。

challenge icon

挑战

中等

让我们通过创建一个简单的购物清单管理器,来练习在 Go 中使用切片!

你的任务是实现几个用于操作购物清单的函数:

  1. addItems:向购物清单添加新商品
  2. removeItem:根据索引从清单中移除商品
  3. findExpensiveItems:查找价格高于指定阈值的商品
  4. calculateTotalCost:计算所有商品的总价

购物清单中的每件商品由一个字符串(名称)和一个 float64(价格)表示。main 函数演示了如何将这些操作组合起来使用。

亲手试试

package main

import "fmt"

// addItems 将新商品及其价格添加到购物列表
func addItems(names []string, prices []float64, newNames []string, newPrices []float64) ([]string, []float64) {
	// 在这里编写你的代码
	return names, prices
}

// removeItem 移除指定索引处的商品
func removeItem(names []string, prices []float64, index int) ([]string, []float64) {
	// 在这里编写你的代码
	return names, prices
}

// findExpensiveItems 返回价格高于阈值的商品
func findExpensiveItems(names []string, prices []float64, threshold float64) []string {
	// 在这里编写你的代码
	return nil
}

// calculateTotalCost 返回所有价格的总和
func calculateTotalCost(prices []float64) float64 {
	// 在这里编写你的代码
	return 0
}

func main() {
	// 初始化空购物列表
	names := []string{}
	prices := []float64{}
	
	// 添加初始商品
	initialNames := []string{"Apples", "Milk", "Bread"}
	initialPrices := []float64{2.99, 3.49, 2.29}
	
	names, prices = addItems(names, prices, initialNames, initialPrices)
	
	// 输出初始购物列表
	fmt.Println("Initial Shopping List:")
	for i := range names {
		fmt.Printf("%d. %s - $%.2f\n", i, names[i], prices[i])
	}
	
	// 计算并输出总费用
	total := calculateTotalCost(prices)
	fmt.Printf("\nTotal Cost: $%.2f\n", total)
	
	// 查找并输出价格较高的商品
	priceThreshold := 3.00
	expensiveItems := findExpensiveItems(names, prices, priceThreshold)
	
	fmt.Printf("\nExpensive Items (above $%.2f):\n", priceThreshold)
	for _, item := range expensiveItems {
		fmt.Println(item)
	}
	
	// 添加一件新商品
	names, prices = addItems(names, prices, []string{"Cheese"}, []float64{4.99})
	
	// 移除一件商品
	names, prices = removeItem(names, prices, 1)
	fmt.Println("\nRemoved item at index 1")
	
	// 打印最终的购物列表
	fmt.Println("\nFinal Shopping List:")
	for i := range names {
		fmt.Printf("%d. %s - $%.2f\n", i, names[i], prices[i])
	}
}

基础知识中的所有课

自己练习: Go 在线编译器