Software & Finance





Visual C++ - Finding the Intersection of two Lines Given Slope and Intercept of Two Lines





Here is the Visual C++ program for Finding the Intersection of two Lines Given Slope and Intercept of Two Lines.

 

We directly got the equation for the two lines Y = MX + C as input.

 

Where M = Slope of a Line and C = Intercept

 

If the difference between the slope of two lines are ZERO, then there is no intersection.

Otherwise the intersecting point is calculated using the following formula:

 

intersection_X = (c2 - c1) / (m1 - m2);

intersection_Y = m1 * intersection_X + c1;

 

Where c1 and c2 are intercepts of two lines and m1 and m2 are slope for the two lines.

 

NOTE: This program does not guarantee that the intersecting point lies on the line or not. It just informs us the projected lines from the either direction using the line equation will meet at some point. To get the intersecting point of two line segments in which the intersecting point lies on the two lines, click here.

 


Source Code


#include <iostream>

#include <math.h>

 

void main()

{

    float m1, c1, m2, c2;

    float intersection_X, intersection_Y;

 

    std::cout << "Program to find the intersecting point of two lines:\n";

 

    std::cout << "Enter Line1 - Slope: ";

    std::cin >> m1;

 

    std::cout << "Enter Line1 - Intercept: ";

    std::cin >> c1;

 

    std::cout << "Enter Line2 - Slope: ";

    std::cin >> m2;

 

    std::cout << "Enter Line2 - Intercept: ";

    std::cin >> c2;

 

    std::cout << "Equation of line1: ";

    std::cout << m1 << "X " << ((c1 < 0) ? ' ' : '+') << c1 << "\n";

   

    std::cout << "Equation of line2: ";

    std::cout << m2 << "X " << ((c2 < 0) ? ' ' : '+') << c2 << "\n";

 

    if( (m1 - m2) == 0)

        std::cout << "No Intersection between the lines\n";

    else

    {

        intersection_X = (c2 - c1) / (m1 - m2);

        intersection_Y = m1 * intersection_X + c1;

        std::cout << "Intersecting Point: = ";

        std::cout << intersection_X;

        std::cout << ",";

        std::cout << intersection_Y;

        std::cout << "\n";

    }

}

Output


 

Program to find the intersecting point of two lines:

Enter Line1 - Slope: 1.25

Enter Line1 - Intercept: 0.75

Enter Line2 - Slope: 2

Enter Line2 - Intercept: -3

Equation of line1: 1.25X +0.75

Equation of line2: 2X  -3

Intersecting Point: = 5,7

Press any key to continue . . .