Prompt
Answer
Certainly! Below is a professional-grade C++ code snippet to calculate the Body Mass Index (BMI), complete with all necessary elements such as a docstring, input validation, and comments.
BMI Calculation in C++
Overview
This program defines a function to calculate the Body Mass Index (BMI). The BMI is calculated using the formula:
[ BMI = \frac{\text{weight (kg)}}{(\text{height (m)})^2} ]
Code
#include
#include
/**
* @brief Calculates the Body Mass Index (BMI).
*
* @param weight The weight of the person in kilograms. Should be a positive number.
* @param height The height of the person in meters. Should be a positive number.
* @return double The calculated BMI.
* @throws std::invalid_argument if weight or height are not positive numbers.
*/
double calculateBMI(double weight, double height) {
// Input validation
if (weight <= 0) {
throw std::invalid_argument("Weight must be a positive number.");
}
if (height <= 0) {
throw std::invalid_argument("Height must be a positive number.");
}
// Calculate BMI using the formula
double bmi = weight / (height * height);
return bmi;
}
int main() {
try {
double weight, height;
// Input from user
std::cout << "Enter your weight in kilograms: ";
std::cin >> weight;
std::cout << "Enter your height in meters: ";
std::cin >> height;
// Calculate and display the BMI
double bmi = calculateBMI(weight, height);
std::cout << "Your BMI is: " << bmi << std::endl;
}
catch (const std::invalid_argument &e) {
// Handle invalid arguments gracefully
std::cerr << "Error: " << e.what() << std::endl;
}
return 0;
}
Code Explanation
- Libraries Included: The program includes
for input and output operations and for handling exceptions. - calculateBMI Function:
- Parameters:
weight
(in kilograms) andheight
(in meters). - Return Type:
double
- the calculated BMI. - Exceptions: Throws
std::invalid_argument
if either weight or height are not positive. - Logic: Validates inputs and calculates BMI using the given formula.
- Parameters:
- Main Function:
- Prompts the user for weight and height.
- Calls the
calculateBMI
function and displays the BMI. - Catches and handles any exceptions related to invalid input gracefully.
Usage Example
Here's a practical example of how the program can be used:
// Sample Input/Output
// Enter your weight in kilograms: 70
// Enter your height in meters: 1.75
// Your BMI is: 22.8571
This program ensures the input is valid and provides informative error messages, exemplifying robust and professional C++ code design. For further learning and courses on similar topics, consider exploring the Enterprise DNA platform.
Description
This C++ program calculates the Body Mass Index (BMI) by validating user inputs for weight and height, performing the calculation, and gracefully handling errors through exceptions.