Print Line Equation y = mx + b
In this step, you will learn how to print the complete line equation using the slope and y-intercept calculated in the previous steps. We'll modify the existing C program to display the line equation in the standard form y = mx + b.
Continue working in the same project directory:
cd ~/project
nano line_equation_final.c
Write the following C code to print the line equation:
#include <stdio.h>
float calculate_slope(float x1, float y1, float x2, float y2) {
if (x2 - x1 == 0) {
printf("Undefined slope (vertical line)\n");
return 0;
}
return (y2 - y1) / (x2 - x1);
}
float calculate_intercept(float x, float y, float slope) {
return y - (slope * x);
}
void print_line_equation(float slope, float intercept) {
printf("Line Equation: y = ");
// Print slope coefficient
if (slope == 1) {
printf("x");
} else if (slope == -1) {
printf("-x");
} else if (slope != 0) {
printf("%.2fx", slope);
}
// Print intercept
if (intercept > 0) {
printf(" + %.2f", intercept);
} else if (intercept < 0) {
printf(" - %.2f", -intercept);
}
printf("\n");
}
int main() {
float x1 = 2.0, y1 = 3.0; // First point
float x2 = 5.0, y2 = 7.0; // Second point
float slope = calculate_slope(x1, y1, x2, y2);
float intercept = calculate_intercept(x1, y1, slope);
printf("Point 1: (%.1f, %.1f)\n", x1, y1);
printf("Point 2: (%.1f, %.1f)\n", x2, y2);
printf("Slope: %.2f\n", slope);
printf("Y-intercept: %.2f\n", intercept);
print_line_equation(slope, intercept);
return 0;
}
Compile and run the program:
gcc line_equation_final.c -o line_equation_final
./line_equation_final
Example output:
Point 1: (2.0, 3.0)
Point 2: (5.0, 7.0)
Slope: 1.33
Y-intercept: 0.33
Line Equation: y = 1.33x + 0.33
Let's break down the new code:
- The
print_line_equation()
function handles different cases of slope and intercept
- It handles special cases like slope of 1, -1, or 0
- It formats the equation with proper signs for the intercept
- The function provides a clean, readable representation of the line equation
The code demonstrates how to convert point and slope information into a standard linear equation format.