Scale a Recipe Up or Down Based on the Number of Servings
Introduction
Scaling a recipe is a common task when adjusting portions for different numbers of servings. Whether you’re cooking for a small group or hosting a large event, it’s essential to modify the quantities of ingredients accordingly. This C++ program helps automate the process by allowing users to scale ingredients based on the desired number of servings.
Objective
The objective of this program is to allow users to input the number of servings they need and then scale the ingredients of a recipe to match. The program will adjust the quantities based on the ratio of desired servings to original servings.
C++ Program to Scale a Recipe
#include <iostream> using namespace std; int main() { double originalServings, desiredServings; double ingredientQuantity; // Ask for original servings and desired servings cout << "Enter the number of servings in the original recipe: "; cin >> originalServings; cout << "Enter the number of servings you want to prepare: "; cin >> desiredServings; // Calculate the scaling factor double scalingFactor = desiredServings / originalServings; // Loop to adjust the ingredient quantities cout << "\nEnter the quantities of ingredients (type a negative number to stop):\n"; while (true) { cout << "Enter ingredient quantity: "; cin >> ingredientQuantity; if (ingredientQuantity < 0) { break; // Stop if the user inputs a negative value } // Scale the ingredient quantity ingredientQuantity *= scalingFactor; cout << "Scaled ingredient quantity: " << ingredientQuantity << endl; } return 0; }
Explanation of the Program
This program performs the following steps:
- It first prompts the user to enter the number of servings in the original recipe.
- Next, the user is asked to input the desired number of servings for the recipe.
- The program calculates a scaling factor, which is the ratio of desired servings to original servings.
- The user is then prompted to enter the ingredient quantities. The program will scale each ingredient by multiplying its quantity with the scaling factor.
- The program continues asking for ingredient quantities until the user inputs a negative number.
How to Run the Program:
To run this program:
- Save the code to a file with the “.cpp” extension (e.g., “scale_recipe.cpp”).
- Compile the program using a C++ compiler (e.g., using the command:
g++ scale_recipe.cpp -o scale_recipe
). - Run the compiled program (e.g.,
./scale_recipe
on Unix-based systems orscale_recipe.exe
on Windows). - Follow the on-screen prompts to input the number of servings and the ingredient quantities.