I know that there are many sites that explain how to check the intersection of two lines, but I am very bored just copying and pasting the code for such a simple math problem. The more I get disappointed, the more I can't get my code to work. I know questions with "What's wrong with my code?" are stupid, but I don’t know what the hell is wrong with my math / code, also my code is well documented (except, in truth, the wrong naming of variables), so I think there should be someone who interested in math behind her
bool segment::checkforIntersection(QPointF a, QPointF b) {
QPointF bx = b-a;
double firstGradient = bx.y() / bx.x();
double firstOffset = a.y() - firstGradient * a.x();
double secondGradient, secondOffset;
for (int i = 0; i < poscount-3; i++) {
QPointF c = pos[i];
QPointF d = pos[i+1];
QPointF dx = d-c;
secondGradient = dx.y() / dx.x();
secondOffset = c.y() - secondGradient * c.x();
double x = (firstOffset - secondOffset) / (secondGradient - firstGradient);
if (x >= a.x() && x <= b.x() && x >= c.x() && x <= d.x()) {
return true;
}
}
return false;
}
, , 4 a, b, c, d ( 1: a - b, 2: c - d) ( for), x y, , deltay/deltax. , , a ( c ) . , 4 a + bx, ax of 0 , (a/c), ax of 1 , (b/). ( ). , x. , . - ?
, . Positives (, , ), (, ). , , , , , , .
, , ( -), , , - .:)
: , Qt, ++:
#include <iostream>
#include <math.h>
using namespace std;
class Point {
private:
double xval, yval;
public:
Point(double x = 0.0, double y = 0.0) {
xval = x;
yval = y;
}
double x() { return xval; }
double y() { return yval; }
Point sub(Point b)
{
return Point(xval - b.xval, yval - b.yval);
}
};
bool checkforIntersection(Point a, Point b, Point c, Point d) {
Point bx = b.sub(a);
double firstGradient = bx.y() / bx.x();
double firstOffset = a.y() - firstGradient * a.x();
double secondGradient, secondOffset;
Point dx = d.sub(c);
secondGradient = dx.y() / dx.x();
secondOffset = c.y() - secondGradient * c.x();
double x = (firstOffset - secondOffset) / (secondGradient - firstGradient);
if (x >= a.x() && x <= b.x() && x >= c.x() && x <= d.x()) {
return true;
}
return false;
}
int main(int argc, char const *argv[]) {
if (checkforIntersection(Point(310.374,835.171),Point(290.434,802.354), Point(333.847,807.232), Point(301.03,827.172)) == true) {
cout << "These lines do intersect so I should be printed out\n";
} else {
cout << "The algorithm does not work, so instead I do get printed out\n";
}
return 0;
}
, ~ (310,835) - (290,802) (333,807) - (301,827). :
\documentclass[crop,tikz]{standalone}
\begin{document}
\begin{tikzpicture}[x=.1cm,y=.1cm]
\draw (310,835) -- (290,802);
\draw (333,807) -- (301,827);
\end{tikzpicture}
\end{document}
++ ,