用所涉及的垂直线评估交叉点

时间:2015-09-30 10:26:24

标签: c++ function return-value

这是一个返回由点p0, p1p2, p3定义的两条线之间的交点的函数:

#include "std_lib_facilities.h"
#include <iostream>

struct Point{
    Point(int xx, int yy): x(xx), y(yy) { }
int x;
int y;
};

// find the intersection of two lines
Point intersectPoint(Point& p0, Point& p1, Point& p2, Point& p3){
    // line formed by p0p1
    double dx1 = p1.x - p0.x;
    double dy1 = p1.y - p0.y;
    double m1 = dy1 / dx1;
    double c1 = p1.y - m1 * p1.x;
    cout <<"m1: "<< m1 <<'\n'; 
    // line formed by p2p3
    double dx2 = p3.x - p2.x;
    double dy2 = p3.y - p2.y;
    double m2 = dy2 / dx2;
    double c2 = p3.y - m1 * p3.x;
    cout <<"m2: "<< m2 <<'\n';
    // find intersection point
    double epsilon = 1e-6;
    // (-1,-1) represents no intersection 
    if (abs(m1 - m2) < epsilon) return Point(-1,-1);
    else{
       double interX = (c2 - c1) / (m1 - m2);
       double interY = m1 * interX + c1;
       cout <<"(interX, interY): "<< interX <<", "<< interY <<'\n';
       return Point(interX, interY);
   }
}
//------------------------------------------------------------------------------------------------
int main(){ 
    Point verticalStart(100, 100);
    Point verticalEnd(100,300);

    Point horizontalStart(50,200);
    Point horizontalEnd(150,200);

    Point intersection = intersectPoint(horizontalStart ,horizontalEnd, verticalStart, verticalEnd);
    cout <<"returned value: \n"; 
    cout << "( "<< intersection.x <<", "<< intersection.y <<" )\n"; 

    getchar();
    return 0;
}

在垂直和水平交叉的情况下,我得到一个输出:

m1: 0
m2: 1.#inf
(interX, interY): -0, 200
returned value:
( 0, 200 )

问题:

如何处理这种情况,以便函数返回有效的交点?

注意:代码是在MVS2010上编译的。

1 个答案:

答案 0 :(得分:2)

我建议不要使用斜率截距表示法,即:y = a*x + b,而是使用矢量参数表示法:

Pa = (P1-P0)*t + P0
Pb = (P3-P2)*u + P2

这样,行x = k确实有一个表示。

解决系统变量tu(2个变量,两个方程式,两个坐标xyPa = Pb( (交点)并在这些方程之一中进行反向替换以得到交点。