Menu
Coddy logo textTech

Özet - İşaretçileri Anlamak

Coddy'nin GO Journey'sinin Temeller bölümünün bir parçası. Ders 66 / 109.

challenge icon

Görev

Orta

Bu meydan okumada, küçük bir mağaza için basit bir envanter yönetim sistemi oluşturacaksın. Envanter miktarlarını güncellemek, değerleri hesaplamak ve değişiklikleri takip etmek için işaretçiler kullanacaksın.

Aşağıdaki üç işlevi tamamla:

  1. updateQuantity(quantity *int, change int) (int, bool)
    quantity değerini ekleyerek change konumundaki değeri değiştir (satışlar için negatif, yeniden stoklama için pozitif).
    Sonuç 0 değerinin altına düşecekse bunun yerine *quantity değerini 0 olarak ayarla.
    Yeni miktarı ve ürünün artık stokta kalmadığını (true) belirten bir boole değeri döndür; ürün stokta kalmadıysa bu değer *quantity == 0 olmalıdır.
  2. calculateValue(itemName string, quantity int, price float64, mostValuableItem *string, highestValue *float64) float64
    totalValue değerini float64(quantity) * price olarak hesapla.
    totalValue değeri *highestValue değerinden büyükse *highestValue değerini güncelle ve işaretçileri kullanarak *mostValuableItem değerini itemName olarak ayarla.
    totalValue değerini döndür.
  3. displayInventory(apples, oranges, bananas *int, applePrice, orangePrice, bananaPrice float64)
    fmt.Printf kullanarak her ürünün adını, miktarını (işaretçisinden başvurusu kaldırılmış olarak) ve hesaplanan değerini yazdır.
    Biçim: Apples: 10 (Value: $5.00): fiyatlar için %.2f kullan.

Başlangıç envanteri için beklenen çıktı şöyledir:

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

İpucu: Bir işaretçinin işaret ettiği değeri okumak veya yazmak için *quantity kullan. Örneğin, *quantity += change özgün değişkeni doğrudan değiştirir.

Kendin dene

package main

import "fmt"

// updateQuantity bir öğenin miktarını günceller ve yeni miktarı döndürür
// ve öğenin stokta olup olmadığını (quantity = 0)
func updateQuantity(quantity *int, change int) (int, bool) {
    // TODO: quantity işaretçisini güncelleyin ve yeni değeri ile stokta olmama durumunu döndürün
    return 0, false
}

// calculateValue miktar ve fiyata göre bir öğenin toplam değerini hesaplar
// It also updates the mostValuableItem if this item is more valuable
func calculateValue(itemName string, quantity int, price float64, mostValuableItem *string, highestValue *float64) float64 {
    // TODO: Calculate the total value, update mostValuableItem if needed, and return the total value
    return 0.0
}

// displayInventory envanter detaylarını yazdırır
// İşlevin gerçek zamanlı verileri göstermesine olanak sağlamak için işaretçiler alır
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() {
    // Envanteri başlat
    apples := 10
    oranges := 15
    bananas := 8
    
    // Fiyatlar
    applePrice := 0.5  // $0.50 her biri
    orangePrice := 0.7 // $0.70 her biri
    bananaPrice := 0.3 // $0.30 her biri
    
    // Track the most valuable item
    var mostValuableItem string
    var highestValue float64
    
    // Display initial inventory
    fmt.Println("Initial Inventory:")
    displayInventory(&apples, &oranges, &bananas, applePrice, orangePrice, bananaPrice)
    
    // Calculate initial values and find most valuable item
    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)
    
    // Bazı satışları simüle et
    fmt.Println("Processing sales...")
    _, applesOutOfStock := updateQuantity(&apples, -4) // 4 elma sat
    _, orangesOutOfStock := updateQuantity(&oranges, -8) // 8 portakal sat
    _, bananasOutOfStock := updateQuantity(&bananas, -10) // 10 muz satmayı dene (elimizdekinden fazla)
    
    // Check if any items are out of stock
    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!")
    }
    
    // Display updated inventory
    fmt.Println("\nUpdated Inventory:")
    displayInventory(&apples, &oranges, &bananas, applePrice, orangePrice, bananaPrice)
    
    // Reset most valuable tracking for recalculation
    mostValuableItem = ""
    highestValue = 0
    
    // Değerleri yeniden hesapla
    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)
    
    // Ürünleri yeniden stokla
    fmt.Println("Restocking...")
    updateQuantity(&apples, 5)  // 5 elma ekle
    updateQuantity(&oranges, 10) // 10 portakal ekle
    updateQuantity(&bananas, 12) // 12 muz ekle
    
    // Display final inventory
    fmt.Println("\nFinal Inventory:")
    displayInventory(&apples, &oranges, &bananas, applePrice, orangePrice, bananaPrice)
    
    // Reset most valuable tracking for final calculation
    mostValuableItem = ""
    highestValue = 0
    
    // Son değer hesaplaması
    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)
}

Temeller bölümündeki tüm dersler

Kendi başına pratik yap: Online Go derleyicisi