Visual C++ - Finding the equation of a Line Given Two End Points
Here is the Visual C++ program for finding the equation of a Line Given Two End Points (x1,y1) and (x2, y2)
The equation for a line is Y = MX + C
Where M = Slope of a Line and C = Intercept
To Find the slope of a line
slope = (y2 - y1) / (x2 - x1)
To Find the intercept of the line, intercept = y1 - (slope) * x1
which would be same as, intercept = y2 - (slope) * x2
Source Code
#include <iostream>
#include <math.h>
void main()
{
float slope, intercept;
float x1, y1, x2, y2;
float dx, dy;
std::cout << "Program to find the equation of a line given two end points\n";
std::cout << "Enter X1: ";
std::cin >> x1;
std::cout << "Enter Y1: ";
std::cin >> y1;
std::cout << "Enter X2: ";
std::cin >> x2;
std::cout << "Enter Y2: ";
std::cin >> y2;
dx = x2 - x1;
dy = y2 - y1;
slope = dy / dx;
// y = mx + c
// intercept c = y - mx
intercept = y1 - slope * x1; // which is same as y2 - slope * x2
std::cout << "Equation of the line with end points (" << x1 << ", " << y1 << ") and (" << x2 << ", " << y2 << ") : Y = ";
std::cout << slope << "X " << ((intercept < 0) ? ' ' : '+') << intercept << "\n";
}
Output
Program to find the equation of a line given two end points
Enter X1: 2
Enter Y1: 3
Enter X2: 5
Enter Y2: 7
Equation of the line with end points (2, 3 and (5, 7) : Y = 1.33333X +0.333333
Press any key to continue . . .
|