Print the Slope
In this final step, you will enhance the slope calculation program by adding more detailed output and formatting the slope presentation. We'll improve the user experience by providing clear, informative slope information.
Open the previous file and update the code:
cd ~/project
nano slope_calculator.c
Replace the contents with the following code:
#include <stdio.h>
#include <math.h>
int main() {
float x1, y1, x2, y2, slope;
// Prompt user to enter first point coordinates
printf("Slope Calculator\n");
printf("================\n");
printf("Enter the x-coordinate of the first point (x1): ");
scanf("%f", &x1);
printf("Enter the y-coordinate of the first point (y1): ");
scanf("%f", &y1);
// Prompt user to enter second point coordinates
printf("Enter the x-coordinate of the second point (x2): ");
scanf("%f", &x2);
printf("Enter the y-coordinate of the second point (y2): ");
scanf("%f", &y2);
// Check for vertical line (undefined slope)
if (x2 == x1) {
printf("\nResult:\n");
printf("First point: (%.2f, %.2f)\n", x1, y1);
printf("Second point: (%.2f, %.2f)\n", x2, y2);
printf("Slope: Undefined (Vertical Line)\n");
return 0;
}
// Calculate slope
slope = (y2 - y1) / (x2 - x1);
// Print detailed results
printf("\nResult:\n");
printf("First point: (%.2f, %.2f)\n", x1, y1);
printf("Second point: (%.2f, %.2f)\n", x2, y2);
printf("Slope Calculation: (%.2f - %.2f) / (%.2f - %.2f) = %.2f\n",
y2, y1, x2, x1, slope);
// Additional slope interpretation
if (slope > 0) {
printf("Slope Interpretation: Positive slope (line rises from left to right)\n");
} else if (slope < 0) {
printf("Slope Interpretation: Negative slope (line falls from left to right)\n");
} else {
printf("Slope Interpretation: Horizontal line (zero slope)\n");
}
return 0;
}
Compile and run the program:
gcc slope_calculator.c -o slope_calculator
./slope_calculator
Example output:
Slope Calculator
================
Enter the x-coordinate of the first point (x1): 1
Enter the y-coordinate of the first point (y1): 2
Enter the x-coordinate of the second point (x2): 4
Enter the y-coordinate of the second point (y2): 6
Result:
First point: (1.00, 2.00)
Second point: (4.00, 6.00)
Slope Calculation: (6.00 - 2.00) / (4.00 - 1.00) = 1.33
Slope Interpretation: Positive slope (line rises from left to right)