Menu
Coddy logo textTech

Ripasso - Capire i puntatori

Fa parte della sezione Fondamenti del percorso GO di Coddy. Lezione 66 di 109.

challenge icon

Sfida

Medio

In questa sfida creerai un semplice sistema di gestione dell'inventario per un piccolo negozio. Userai i puntatori per aggiornare le quantità dell'inventario, calcolare i valori e tenere traccia delle modifiche.

Completa le tre funzioni seguenti:

  1. updateQuantity(quantity *int, change int) (int, bool)
    Modifica il valore a cui punta quantity aggiungendo change (negativo per le vendite, positivo per i rifornimenti).
    Se il risultato scenderebbe sotto 0, imposta invece *quantity su 0.
    Restituisci la nuova quantità e un booleano che è true se l'articolo è ora esaurito (*quantity == 0).
  2. calculateValue(itemName string, quantity int, price float64, mostValuableItem *string, highestValue *float64) float64
    Calcola totalValue come float64(quantity) * price.
    Se totalValue è maggiore di *highestValue, aggiorna *highestValue e imposta *mostValuableItem su itemName usando i puntatori.
    Restituisci totalValue.
  3. displayInventory(apples, oranges, bananas *int, applePrice, orangePrice, bananaPrice float64)
    Stampa il nome e la quantità di ogni articolo (dereferenziata dal suo puntatore) e il valore calcolato usando fmt.Printf.
    Formato: Apples: 10 (Value: $5.00): usa %.2f per i prezzi.

L'output previsto per l'inventario iniziale è:

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

Suggerimento: Usa *quantity per leggere o scrivere il valore a cui punta un puntatore. Per esempio, *quantity += change modifica direttamente la variabile originale.

Provalo tu

package main

import "fmt"

// updateQuantity aggiorna la quantità di un articolo e restituisce la nuova quantità
// e indica se l'articolo è esaurito (quantity = 0)
func updateQuantity(quantity *int, change int) (int, bool) {
    // TODO: Aggiornare il valore a cui punta quantity e restituire il nuovo valore e lo stato di esaurimento
    return 0, false
}

// calculateValue calcola il valore totale di un articolo in base alla quantità e al prezzo
// Aggiorna anche mostValuableItem se questo articolo ha un valore maggiore
func calculateValue(itemName string, quantity int, price float64, mostValuableItem *string, highestValue *float64) float64 {
    // TODO: Calcolare il valore totale, aggiornare mostValuableItem se necessario e restituire il valore totale
    return 0.0
}

// displayInventory stampa i dettagli dell'inventario
// Accetta puntatori per consentire alla funzione di mostrare i dati aggiornati in tempo reale
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() {
    // Inizializza l'inventario
    apples := 10
    oranges := 15
    bananas := 8
    
    // Prezzi
    applePrice := 0.5  // $0.50 ciascuna
    orangePrice := 0.7 // $0.70 ciascuna
    bananaPrice := 0.3 // $0.30 ciascuna
    
    // Tieni traccia dell'articolo di maggior valore
    var mostValuableItem string
    var highestValue float64
    
    // Mostra l'inventario iniziale
    fmt.Println("Initial Inventory:")
    displayInventory(&apples, &oranges, &bananas, applePrice, orangePrice, bananaPrice)
    
    // Calcola i valori iniziali e trova l'articolo di maggior valore
    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)
    
    // Simula alcune vendite
    fmt.Println("Processing sales...")
    _, applesOutOfStock := updateQuantity(&apples, -4) // Vendi 4 mele
    _, orangesOutOfStock := updateQuantity(&oranges, -8) // Vendi 8 arance
    _, bananasOutOfStock := updateQuantity(&bananas, -10) // Prova a vendere 10 banane (più di quelle disponibili)
    
    // Controlla se qualche articolo è esaurito
    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!")
    }
    
    // Mostra l'inventario aggiornato
    fmt.Println("\nUpdated Inventory:")
    displayInventory(&apples, &oranges, &bananas, applePrice, orangePrice, bananaPrice)
    
    // Azzera il monitoraggio dell'articolo di maggior valore per ricalcolarlo
    mostValuableItem = ""
    highestValue = 0
    
    // Ricalcola i valori
    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)
    
    // Riassortisci gli articoli
    fmt.Println("Restocking...")
    updateQuantity(&apples, 5)  // Aggiungi 5 mele
    updateQuantity(&oranges, 10) // Aggiungi 10 arance
    updateQuantity(&bananas, 12) // Aggiungi 12 banane
    
    // Mostra l'inventario finale
    fmt.Println("\nFinal Inventory:")
    displayInventory(&apples, &oranges, &bananas, applePrice, orangePrice, bananaPrice)
    
    // Azzera il monitoraggio dell'articolo di maggior valore per il calcolo finale
    mostValuableItem = ""
    highestValue = 0
    
    // Calcolo del valore finale
    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)
}

Tutte le lezioni di Fondamenti

Esercitati da solo: Compilatore Go online