Imprimir la pendiente
En este último paso, mejorará el programa de cálculo de la pendiente agregando una salida más detallada y formateando la presentación de la pendiente. Mejoraremos la experiencia del usuario proporcionando información clara e informativa sobre la pendiente.
Abra el archivo anterior y actualice el código:
cd ~/project
nano slope_calculator.c
Reemplace el contenido con el siguiente código:
#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 y ejecute el programa:
gcc slope_calculator.c -o slope_calculator
./slope_calculator
Ejemplo de salida:
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)