Check if two line segments intersect

Hi,

I've written some code below to check if two line segments intersect and if they do to tell me where. As input I have the (x,y) coordinates of both ends of each line. It appeared to be working correctly but now in the scenario where line A (532.87,787.79)(486.34,769.85) and line B (490.89,764.018)(478.98,783.129) it says they intersect at (770.136, 487.08) when the lines don' intersect at all.

Has anyone any idea what is incorrect in the below code? Thanks in advance

Code:

`dy[0] = y2 - y1;`

dx[0] = x2 - x1;

dy[1] = y4 - y3;

dx[1] = x4 - x3;

m[0] = dy[0] / dx[0];

m[1] = dy[1] / dx[1];

b[0] = y1 - m[0] * x1;

b[1] = y3 - m[1] * x3;

if (m[0] != m[1])

{

//slopes not equal, compute intercept

xint = (b[0] - b[1]) / (m[1] - m[0]);

yint = m[1] * xint + b[1];

//is intercept in both line segments?

if ((xint <= max(x1, x2)) && (xint >= min(x1, x2)) &&

(yint <= max(y1, y2)) && (yint >= min(y1, y2)) &&

(xint <= max(x3, x4)) && (xint >= min(x3, x4)) &&

(yint <= max(y3, y4)) && (yint >= min(y3, y4)))

{

if (xi && yi)

{

xi = xint;

yi = yint;

location_msg_ptr->current_latitude = xi;

location_msg_ptr->current_longitude = yi;

}

return(location_msg_ptr);

}

}

return(location_msg_ptr);

}