c++line-intersection

inf output computing line slopes


I am very new at C++.

I wrote this code below which is supposed to tell me if 2 lines have an intersection point, so I figured two lines with equal "M" in the y=Mx+B equation should not intersect and all others would.

The program seems to be understanding this, but unless the slope of the inputted line segment is 0 it outputs inf or -inf.

why is this happening?

#include <iostream>
using namespace std;
int main ()
{
typedef double vector2d[2];
vector2d pointA, pointB, pointC, pointD;
double LineSeg1, LineSeg2;
double yes, no;


cout << "Enter x for point A: ";
cin >> pointA[0];
cout << "Enter y for point A: ";
cin >> pointA[1];
cout << "Point A = (" << pointA[0] << "," << pointA[1] << ")" << endl;

cout << "Enter x for point B: ";
cin >> pointB[0];
cout << "Enter y for point B: ";
cin >> pointB[1];
cout << "Point B = (" << pointB[0] << "," << pointB[1] << ")" << endl;

cout << "Enter x for point C: ";
cin >> pointC[0];
cout << "Enter y for point C: ";
cin >> pointC[1];
cout << "Point C = (" << pointC[0] << "," << pointC[1] << ")" << endl;

cout << "Enter x for point D: ";
cin >> pointD[0];
cout << "Enter y for point D: ";
cin >> pointD[1];
cout << "Point D = (" << pointD[0] << "," << pointD[1] << ")" << endl;

LineSeg1 = ((pointB[1]-pointA[1])/(pointB[0]-pointB[0]));
cout << "slope segment 1 = (" << LineSeg1 << endl;

LineSeg2 = ((pointD[1]-pointC[1])/(pointD[0]-pointC[0]));
cout << "slope segment 2 = (" << LineSeg2 << endl;


if ( LineSeg1 == LineSeg2 ) {
    cout << "no\n";
}

else ( LineSeg1 != LineSeg2 ) ;{
    cout << "yes\n";
}

return 0;

}

Solution

  • This line:

    LineSeg1 = ((pointB[1]-pointA[1])/(pointB[0]-pointB[0]));
    

    has a divide by zero error.

    I believe the equation should be:

    LineSeg1 = ((pointB[1]-pointA[1])/(pointB[0]-pointA[0]));