Menu
CoddyTech

回顾:理解指针

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

challenge icon

挑战

中等

在这个挑战中,你将为一家小商店构建一个简单的库存管理系统。你将使用指针更新库存数量、计算值并跟踪变化。

完成下面的三个函数:

  1. updateQuantity(quantity *int, change int) (int, bool)
    将 change 加到 quantity 指向的值上(销售时为负数,补货时为正数)。
    如果结果会小于 0,则将 *quantity 设为 0。
    返回新的数量,以及一个布尔值。如果商品现在已售罄(*quantity == 0),该值为 true。
  2. calculateValue(itemName string, quantity int, price float64, mostValuableItem *string, highestValue *float64) float64
    将 totalValue 计算为 float64(quantity) * price。
    如果 totalValue 大于 *highestValue,则使用指针更新 *highestValue,并将 *mostValuableItem 设为 itemName。
    返回 totalValue。
  3. displayInventory(apples, oranges, bananas *int, applePrice, orangePrice, bananaPrice float64)
    使用 fmt.Printf 打印每件商品的名称、数量(从指针中解引用)和计算出的值。
    格式:Apples: 10 (Value: $5.00):价格使用 %.2f。

初始库存的预期输出为:

Initial Inventory:
Apples: 10 (Value: $5.00)
Oranges: 15 (Value: $10.50)
Bananas: 8 (Value: $2.40)
Total inventory value: $17.90
Most valuable item: Oranges

提示:使用 *quantity 读取或写入指针指向的值。例如,*quantity += change 会直接修改原变量。

亲手试试

package main

import "fmt"

// updateQuantity 更新商品数量并返回新数量
// 以及商品是否缺货(quantity = 0)
func updateQuantity(quantity *int, change int) (int, bool) {
    // TODO: 更新 quantity 指针,并返回新值和缺货状态
    return 0, false
}

// calculateValue 根据数量和价格计算商品的总价值
// 如果该商品的价值更高,还会更新 mostValuableItem
func calculateValue(itemName string, quantity int, price float64, mostValuableItem *string, highestValue *float64) float64 {
    // TODO: 计算总价值,必要时更新 mostValuableItem,并返回总价值
    return 0.0
}

// displayInventory 输出库存详情
// 它接收指针,让函数能显示实时数据
func displayInventory(apples, oranges, bananas *int, applePrice, orangePrice, bananaPrice float64) {
    fmt.Printf("Apples: %d (Value: $%.2f)\n", *apples, float64(*apples) * applePrice)
    fmt.Printf("Oranges: %d (Value: $%.2f)\n", *oranges, float64(*oranges) * orangePrice)
    fmt.Printf("Bananas: %d (Value: $%.2f)\n", *bananas, float64(*bananas) * bananaPrice)
}

func main() {
    // 初始化库存
    apples := 10
    oranges := 15
    bananas := 8
    
    // 价格
    applePrice := 0.5  // 每个 $0.50
    orangePrice := 0.7 // 每个 $0.70
    bananaPrice := 0.3 // 每个 $0.30
    
    // 跟踪价值最高的商品
    var mostValuableItem string
    var highestValue float64
    
    // 显示初始库存
    fmt.Println("Initial Inventory:")
    displayInventory(&apples, &oranges, &bananas, applePrice, orangePrice, bananaPrice)
    
    // 计算初始价值并找出价值最高的商品
    appleValue := calculateValue("Apples", apples, applePrice, &mostValuableItem, &highestValue)
    orangeValue := calculateValue("Oranges", oranges, orangePrice, &mostValuableItem, &highestValue)
    bananaValue := calculateValue("Bananas", bananas, bananaPrice, &mostValuableItem, &highestValue)
    
    fmt.Printf("Total inventory value: $%.2f\n", appleValue+orangeValue+bananaValue)
    fmt.Printf("Most valuable item: %s\n\n", mostValuableItem)
    
    // 模拟一些销售
    fmt.Println("Processing sales...")
    _, applesOutOfStock := updateQuantity(&apples, -4) // 卖出 4 个苹果
    _, orangesOutOfStock := updateQuantity(&oranges, -8) // 卖出 8 个橙子
    _, bananasOutOfStock := updateQuantity(&bananas, -10) // 尝试卖出 10 根香蕉(超过现有库存)
    
    // 检查是否有商品缺货
    if applesOutOfStock {
        fmt.Println("Apples are out of stock!")
    }
    if orangesOutOfStock {
        fmt.Println("Oranges are out of stock!")
    }
    if bananasOutOfStock {
        fmt.Println("Bananas are out of stock!")
    }
    
    // 显示更新后的库存
    fmt.Println("\nUpdated Inventory:")
    displayInventory(&apples, &oranges, &bananas, applePrice, orangePrice, bananaPrice)
    
    // 重置价值最高商品的记录,以便重新计算
    mostValuableItem = ""
    highestValue = 0
    
    // 重新计算价值
    appleValue = calculateValue("Apples", apples, applePrice, &mostValuableItem, &highestValue)
    orangeValue = calculateValue("Oranges", oranges, orangePrice, &mostValuableItem, &highestValue)
    bananaValue = calculateValue("Bananas", bananas, bananaPrice, &mostValuableItem, &highestValue)
    
    fmt.Printf("Total inventory value: $%.2f\n", appleValue+orangeValue+bananaValue)
    fmt.Printf("Most valuable item: %s\n\n", mostValuableItem)
    
    // 补充商品库存
    fmt.Println("Restocking...")
    updateQuantity(&apples, 5)  // 增加 5 个苹果
    updateQuantity(&oranges, 10) // 增加 10 个橙子
    updateQuantity(&bananas, 12) // 增加 12 根香蕉
    
    // 显示最终库存
    fmt.Println("\nFinal Inventory:")
    displayInventory(&apples, &oranges, &bananas, applePrice, orangePrice, bananaPrice)
    
    // 重置最有价值商品的记录,以便进行最终计算
    mostValuableItem = ""
    highestValue = 0
    
    // 计算最终价值
    appleValue = calculateValue("Apples", apples, applePrice, &mostValuableItem, &highestValue)
    orangeValue = calculateValue("Oranges", oranges, orangePrice, &mostValuableItem, &highestValue)
    bananaValue = calculateValue("Bananas", bananas, bananaPrice, &mostValuableItem, &highestValue)
    
    fmt.Printf("Total inventory value: $%.2f\n", appleValue+orangeValue+bananaValue)
    fmt.Printf("Most valuable item: %s\n", mostValuableItem)
}

基础知识中的所有课

自己练习: Go 在线编译器