Introduction
Sometimes, when cooking, you need to scale your recipe to match the number of servings you need.
This can be especially useful when hosting parties or adjusting recipes to suit different-sized households.
With the Go programming language, you can easily create a tool to adjust ingredient amounts based on the number of servings required.
This article will guide you through creating a simple Go program to scale a recipe up or down.
Objective
The goal of this program is to allow users to input the original number of servings and the desired number of servings.
The program will then calculate the new quantities for each ingredient based on the scaling factor.
Code Example
package main
import (
"fmt"
)
func main() {
var originalServings, desiredServings int
var ingredientName string
var ingredientAmount float64
// Sample recipe with ingredient quantities for 4 servings
recipe := map[string]float64{
"Flour (cups)": 2.0,
"Sugar (cups)": 1.5,
"Butter (cups)": 1.0,
"Eggs": 2.0,
"Baking Powder (tsp)": 2.0,
}
// Prompt user for original servings and desired servings
fmt.Println("Enter the number of servings in the original recipe:")
fmt.Scan(&originalServings)
fmt.Println("Enter the number of servings you want to prepare:")
fmt.Scan(&desiredServings)
// Scaling factor calculation
scalingFactor := float64(desiredServings) / float64(originalServings)
// Print scaled recipe
fmt.Println("\nScaled Recipe:")
for ingredient, amount := range recipe {
scaledAmount := amount * scalingFactor
fmt.Printf("%s: %.2f\n", ingredient, scaledAmount)
}
}
Explanation of the Program
In this Go program, we begin by defining a map containing the ingredient names and their corresponding quantities for the original recipe.
The user is then prompted to input the number of servings in the original recipe and the desired number of servings.
A scaling factor is calculated by dividing the desired servings by the original servings.
After calculating the scaling factor, the program multiplies each ingredient’s original amount by this factor, producing the new ingredient quantities.
The results are displayed for the user to adjust the recipe according to their desired serving size.
How to Run the Program
To run this program, follow these steps:
-
- Ensure you have Go installed on your system. If not, you can download and install it from here.
- Create a new Go file (e.g.,
recipe_scaler.go
) and copy the code into the file. - Open your terminal or command prompt and navigate to the folder where your Go file is saved.
- Run the following command to execute the program:
go run recipe_scaler.go
- The program will prompt you to enter the original number of servings and the desired number of servings. Enter the values, and the scaled recipe will be displayed.