Calcular la pendiente de una línea en C

CBeginner
Practicar Ahora

Introducción

En este laboratorio, aprenderás cómo calcular la pendiente de una línea utilizando el lenguaje de programación C. El laboratorio cubre dos pasos principales: leer dos puntos (x1, y1) y (x2, y2) a partir de la entrada del usuario, y luego calcular la pendiente utilizando la fórmula (y2 - y1)/(x2 - x1). El programa también manejará el caso especial de una línea vertical. Al final de este laboratorio, tendrás una mejor comprensión de cómo trabajar con conceptos de Cálculo y Geometría Analítica en C.

Leer dos puntos (x1,y1) y (x2,y2)

En este paso, aprenderás cómo leer las coordenadas de dos puntos a partir de la entrada del usuario en un programa en C para calcular la pendiente de una línea. Crearemos un programa simple que solicite al usuario que ingrese las coordenadas x e y de dos puntos.

Primero, creemos un nuevo archivo C en el directorio del proyecto:

cd ~/project
nano slope_calculator.c

Ahora, ingrese el siguiente código para leer dos puntos:

#include <stdio.h>

int main() {
    float x1, y1, x2, y2;

    // Prompt user to enter first point coordinates
    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);

    // Print the entered coordinates
    printf("First point: (%.2f, %.2f)\n", x1, y1);
    printf("Second point: (%.2f, %.2f)\n", x2, y2);

    return 0;
}

Compile y ejecute el programa:

gcc slope_calculator.c -o slope_calculator
./slope_calculator

Ejemplo de salida:

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
First point: (1.00, 2.00)
Second point: (4.00, 6.00)

Calcular la pendiente = (y2 - y1)/(x2 - x1)

En este paso, modificarás el programa anterior para calcular la pendiente de una línea utilizando la fórmula de la pendiente a partir de dos puntos. Agregaremos el cálculo de la pendiente y manejaremos el caso especial de una línea vertical.

Abre el archivo anterior y actualiza el código:

cd ~/project
nano slope_calculator.c

Reemplaza el contenido con el siguiente código:

#include <stdio.h>

int main() {
    float x1, y1, x2, y2, slope;

    // Prompt user to enter first point coordinates
    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("Slope is undefined (vertical line)\n");
        return 0;
    }

    // Calculate slope
    slope = (y2 - y1) / (x2 - x1);

    // Print the results
    printf("First point: (%.2f, %.2f)\n", x1, y1);
    printf("Second point: (%.2f, %.2f)\n", x2, y2);
    printf("Slope: %.2f\n", slope);

    return 0;
}

Compila y ejecuta el programa:

gcc slope_calculator.c -o slope_calculator
./slope_calculator

Ejemplo de salida:

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
First point: (1.00, 2.00)
Second point: (4.00, 6.00)
Slope: 1.33

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)

Resumen

En este laboratorio, aprenderás cómo leer las coordenadas de dos puntos a partir de la entrada del usuario y luego calcular la pendiente de una línea utilizando la fórmula de la pendiente a partir de dos puntos en un programa en C. El programa solicitará al usuario que ingrese las coordenadas x e y de dos puntos, y luego calculará y mostrará la pendiente de la línea. Además, el programa manejará el caso especial de una línea vertical, donde la pendiente es indefinida.

El laboratorio cubre los siguientes pasos clave: 1) Leer dos puntos (x1, y1) y (x2, y2) a partir de la entrada del usuario, y 2) Calcular la pendiente utilizando la fórmula (y2 - y1) / (x2 - x1). Luego, el programa imprimirá la pendiente calculada.