Print the Hypotenuse
In this step, you will enhance the previous program to provide a more formatted and user-friendly output of the hypotenuse calculation.
Open the existing file and update the code:
cd ~/project
nano hypotenuse.c
Modify the code to improve output formatting:
#include <stdio.h>
#include <math.h>
int main() {
float leg1, leg2, hypotenuse;
printf("Right Triangle Hypotenuse Calculator\n");
printf("------------------------------------\n");
printf("Enter the length of the first leg: ");
scanf("%f", &leg1);
printf("Enter the length of the second leg: ");
scanf("%f", &leg2);
// Calculate hypotenuse using Pythagorean theorem
hypotenuse = sqrt(leg1 * leg1 + leg2 * leg2);
// Print formatted results
printf("\nTriangle Measurements:\n");
printf("First Leg: %.2f\n", leg1);
printf("Second Leg: %.2f\n", leg2);
printf("Hypotenuse: %.2f\n", hypotenuse);
// Additional calculation details
printf("\nCalculation Details:\n");
printf("Formula: c = √(a² + b²)\n");
printf(" = √(%.2f² + %.2f²)\n", leg1, leg2);
printf(" = √(%.2f + %.2f)\n", leg1 * leg1, leg2 * leg2);
printf(" = %.2f\n", hypotenuse);
return 0;
}
Compile the program:
gcc hypotenuse.c -o hypotenuse -lm
Run the program and see the detailed output:
./hypotenuse
Example output:
Right Triangle Hypotenuse Calculator
------------------------------------
Enter the length of the first leg: 3
Enter the length of the second leg: 4
Triangle Measurements:
First Leg: 3.00
Second Leg: 4.00
Hypotenuse: 5.00
Calculation Details:
Formula: c = √(a² + b²)
= √(3.00² + 4.00²)
= √(9.00 + 16.00)
= 5.00
Key improvements:
- Added descriptive headers
- Formatted output with aligned columns
- Included step-by-step calculation details
- Improved readability for users