C++ Online Compiler
Example: Calculate Diagonal from Width and Height in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Calculate Diagonal from Width and Height #include <iostream> // For input/output #include <cmath> // For sqrt and pow functions #include <iomanip> // For setting output precision int main() { // Step 1: Declare variables for width, height, and diagonal double width, height, diagonal; // Step 2: Prompt user for width std::cout << "Enter the width of the rectangle: "; std::cin >> width; // Step 3: Prompt user for height std::cout << "Enter the height of the rectangle: "; std::cin >> height; // Step 4: Check for valid input (positive dimensions) if (width <= 0 || height <= 0) { std::cout << "Error: Width and height must be positive values." << std::endl; return 1; // Indicate an error } // Step 5: Calculate the diagonal using the Pythagorean theorem // diagonal = sqrt(width^2 + height^2) diagonal = std::sqrt(std::pow(width, 2) + std::pow(height, 2)); // Step 6: Display the result std::cout << std::fixed << std::setprecision(2); // Format output to 2 decimal places std::cout << "The diagonal of the rectangle is: " << diagonal << std::endl; return 0; // Indicate successful execution }
Output
Clear
ADVERTISEMENTS