Menu
Coddy logo textTech

Récapitulatif - Comprendre les pointeurs

Fait partie de la section Fondamentaux du Journey GO de Coddy. Leçon 66 sur 109.

challenge icon

Défi

Moyen

Dans ce défi, vous allez créer un système simple de gestion des stocks pour un petit magasin. Vous utiliserez des pointeurs pour mettre à jour les quantités en stock, calculer les valeurs et suivre les changements.

Complétez les trois fonctions ci-dessous :

  1. updateQuantity(quantity *int, change int) (int, bool)
    Modifiez la valeur à l'emplacement de quantity en lui ajoutant change (négatif pour les ventes, positif pour les réapprovisionnements).
    Si le résultat devait être inférieur à 0, définissez plutôt *quantity sur 0.
    Renvoyez la nouvelle quantité ainsi qu'une valeur booléenne qui est true si l'article est maintenant en rupture de stock (*quantity == 0).
  2. calculateValue(itemName string, quantity int, price float64, mostValuableItem *string, highestValue *float64) float64
    Calculez totalValue comme float64(quantity) * price.
    Si totalValue est supérieur à *highestValue, mettez à jour *highestValue et définissez *mostValuableItem sur itemName à l'aide des pointeurs.
    Renvoyez totalValue.
  3. displayInventory(apples, oranges, bananas *int, applePrice, orangePrice, bananaPrice float64)
    Affichez le nom de chaque article, sa quantité (déréférencée depuis son pointeur) et sa valeur calculée à l'aide de fmt.Printf.
    Format : Apples: 10 (Value: $5.00) : utilisez %.2f pour les prix.

La sortie attendue pour le stock initial est :

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

Conseil : utilisez *quantity pour lire ou écrire la valeur vers laquelle pointe un pointeur. Par exemple, *quantity += change modifie directement la variable d'origine.

Essayez vous-même

package main

import "fmt"

// updateQuantity met à jour la quantité d'un article et renvoie la nouvelle quantité
// et si l'article est en rupture de stock (quantity = 0)
func updateQuantity(quantity *int, change int) (int, bool) {
    // TODO: Mettre à jour le pointeur de quantité et renvoyer la nouvelle valeur et le statut de rupture de stock
    return 0, false
}

// calculateValue calcule la valeur totale d'un article en fonction de la quantité et du prix
// 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 affiche les détails de l'inventaire
// Elle prend des pointeurs pour permettre à la fonction d'afficher des données en temps réel
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() {
    // Initialiser l'inventaire
    apples := 10
    oranges := 15
    bananas := 8
    
    // Prix
    applePrice := 0.5  // $0.50 chacun
    orangePrice := 0.7 // $0.70 chacun
    bananaPrice := 0.3 // $0.30 chacun
    
    // 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)
    
    // Simuler quelques ventes
    fmt.Println("Processing sales...")
    _, applesOutOfStock := updateQuantity(&apples, -4) // Vendre 4 pommes
    _, orangesOutOfStock := updateQuantity(&oranges, -8) // Vendre 8 oranges
    _, bananasOutOfStock := updateQuantity(&bananas, -10) // Essayer de vendre 10 bananes (plus que ce que nous avons)
    
    // 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
    
    // Recalculer les valeurs
    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éapprovisionner les articles
    fmt.Println("Restocking...")
    updateQuantity(&apples, 5)  // Ajouter 5 pommes
    updateQuantity(&oranges, 10) // Ajouter 10 oranges
    updateQuantity(&bananas, 12) // Ajouter 12 bananes
    
    // Display final inventory
    fmt.Println("\nFinal Inventory:")
    displayInventory(&apples, &oranges, &bananas, applePrice, orangePrice, bananaPrice)
    
    // Reset most valuable tracking for final calculation
    mostValuableItem = ""
    highestValue = 0
    
    // Calcul final de la valeur
    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)
}

Toutes les leçons de Fondamentaux

Entraînez-vous par vous-même : Compilateur Go en ligne