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 construire un système simple de gestion d'inventaire 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'adresse quantity en ajoutant change (négatif pour les ventes, positif pour les réapprovisionnements).
    Si le résultat est inférieur à 0, fixez *quantity à 0 à la place.
    Retournez la nouvelle quantité et un booléen qui vaut 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 avec itemName en utilisant les pointeurs.
    Retournez totalValue.
  3. displayInventory(apples, oranges, bananas *int, applePrice, orangePrice, bananaPrice float64)
    Affichez le nom de chaque article, sa quantité (déréférencée de son pointeur) et sa valeur calculée en utilisant fmt.Printf.
    Format : Apples: 10 (Value: $5.00) — utilisez %.2f pour les prix.

La sortie attendue pour l'inventaire 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 retourne la nouvelle quantité
// et si l'article est en rupture de stock (quantité = 0)
func updateQuantity(quantity *int, change int) (int, bool) {
    // TODO: Mettre à jour le pointeur de quantité et retourner 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
// Elle met également à jour mostValuableItem si cet article a plus de valeur
func calculateValue(itemName string, quantity int, price float64, mostValuableItem *string, highestValue *float64) float64 {
    // TODO: Calculer la valeur totale, mettre à jour mostValuableItem si nécessaire, et retourner la valeur totale
    return 0.0
}

// displayInventory affiche les détails de l'inventaire
// Elle utilise 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
    
    // Suivre l'article ayant le plus de valeur
    var mostValuableItem string
    var highestValue float64
    
    // Afficher l'inventaire initial
    fmt.Println("Initial Inventory:")
    displayInventory(&apples, &oranges, &bananas, applePrice, orangePrice, bananaPrice)
    
    // Calculer les valeurs initiales et trouver l'article ayant le plus de 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\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)
    
    // Vérifier si des articles sont en rupture de 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!")
    }
    
    // Afficher l'inventaire mis à jour
    fmt.Println("\nUpdated Inventory:")
    displayInventory(&apples, &oranges, &bananas, applePrice, orangePrice, bananaPrice)
    
    // Réinitialiser le suivi de l'article le plus précieux pour le recalcul
    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
    
    // Afficher l'inventaire final
    fmt.Println("\nFinal Inventory:")
    displayInventory(&apples, &oranges, &bananas, applePrice, orangePrice, bananaPrice)
    
    // Réinitialiser le suivi de l'article le plus précieux pour le calcul final
    mostValuableItem = ""
    highestValue = 0
    
    // Calcul de la valeur 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)
}

Toutes les leçons de Fondamentaux