Вычисление наклона прямой на языке C

CBeginner
Практиковаться сейчас

Введение

В этом лабораторном занятии вы научитесь вычислять наклон прямой с использованием языка программирования C. В рамках лабораторной работы рассматриваются два основных этапа: считывание двух точек (x1, y1) и (x2, y2) из пользовательского ввода и затем вычисление наклона по формуле (y2 - y1)/(x2 - x1). Программа также будет обрабатывать особый случай вертикальной прямой. По завершении этого лабораторного занятия вы лучше поймете, как работать с концепциями математического анализа и аналитической геометрии на языке C.

Считывание двух точек (x1,y1) и (x2,y2)

На этом этапе вы научитесь считывать координаты двух точек из пользовательского ввода в программе на языке C для вычисления наклона прямой. Мы создадим простую программу, которая попросит пользователя ввести координаты x и y для двух точек.

Сначала создадим новый файл на языке C в директории проекта:

cd ~/project
nano slope_calculator.c

Теперь введите следующий код для считывания двух точек:

#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;
}

Скомпилируйте и запустите программу:

gcc slope_calculator.c -o slope_calculator
./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
First point: (1.00, 2.00)
Second point: (4.00, 6.00)

Вычисление наклона = (y2 - y1)/(x2 - x1)

На этом этапе вы измените предыдущую программу для вычисления наклона прямой с использованием формулы наклона по двум точкам. Мы добавим вычисление наклона и обработку особого случая вертикальной прямой.

Откройте предыдущий файл и обновите код:

cd ~/project
nano slope_calculator.c

Замените содержимое следующим кодом:

#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;
}

Скомпилируйте и запустите программу:

gcc slope_calculator.c -o slope_calculator
./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
First point: (1.00, 2.00)
Second point: (4.00, 6.00)
Slope: 1.33

Вывод наклона

На этом последнем этапе вы улучшите программу для вычисления наклона, добавив более подробный вывод и отформатировав представление наклона. Мы повысим удобство использования программы, предоставляя ясную и информативную информацию о наклоне.

Откройте предыдущий файл и обновите код:

cd ~/project
nano slope_calculator.c

Замените содержимое следующим кодом:

#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;
}

Скомпилируйте и запустите программу:

gcc slope_calculator.c -o slope_calculator
./slope_calculator

Пример вывода:

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)

Резюме

В этом лабораторном занятии вы научитесь считывать координаты двух точек из пользовательского ввода и затем вычислять наклон прямой с использованием формулы наклона по двум точкам в программе на языке C. Программа попросит пользователя ввести координаты x и y для двух точек, а затем вычислит и выведет наклон прямой. Кроме того, программа будет обрабатывать особый случай вертикальной прямой, когда наклон не определен.

В рамках лабораторной работы рассматриваются следующие ключевые этапы: 1) считывание двух точек (x1, y1) и (x2, y2) из пользовательского ввода и 2) вычисление наклона по формуле (y2 - y1) / (x2 - x1). Затем программа выведет вычисленный наклон.