Following is a fragment of a program for deducing whether or out 2 lines intersect.
P and P2 are CPoint objects marking the start and end point of one of the 2 lines.
double m1,m2; //slopes
double b1,b2; //y-intercepts
double y,x; //intersection point
m1=(max(P.y,P2.y) - min(P.y,P2.y)) /( max(P.x,P2.x) - min(P.x,P2.x) );
For some reason I’m always getting m1 to be 0. Why’s that?
If your
CPointclass is a point with integer coordinates, you have to do some conversion here to get the result you want. See the following demonstration of the problem. Consider two pointsP = (1, 4)andP2 = (5, 3):However, in integer division,
1 / 4is0, but you want the result to be0.25. The fact that the result variable has a type ofdoubledoesn’t change the value (and type) of the expression.To solve this problem, you have to cast the parts of your expression just before it becomes relevant that they are to be considered as non-integral numbers. In your case this are the operands of the division, so that it will be a floating point division. (Casting the result of the division will also not help.)
Note that casting the second operand is optional, as
double / intalways uses floating point division.Also note that your expression calculates the absolute value of the slope. You might want to calculate the signed slope.
Something you can improve in your code (this won’t solve the problem above): Instead of subtracting the min of the max of the difference, just take the absolute value of the difference:
Since in C++,
absis a template function (in C it’s a macro, urgh…), you can also force a result type using explicit template types:Also, as the calculation of a slope between two given points seems to be a commonly used function, you can implement this as a free-standing function on two
CPoints:Even better, to make use of C++ templates, implement it on a generic class which has the members
xandy:This solution now works for your
CPointinstance with integer coordinates as well as a (maybe upcoming)CPointFclass with float / double coordinates.As already warned above, this calculates the absolute slope. To change this to a mathematically correct (signed) slope, just replace
abswithstatic_cast: