如何判断点P是否在三角形ABC内?

来源:互联网 发布:免费程序化交易软件 编辑:程序博客网 时间:2024/05/01 00:46

       本题最好不要用直线方程或线段夹角来判断,因为这涉及到分类与讨论,下面的算法是相对比较好的算法,代码如下:

#include<iostream>#include<cmath>using namespace std;typedef struct point{float x;float y;}Point;float side(Point A, Point B){float xLen = A.x - B.x;float yLen = A.y - B.y;return sqrt(xLen * xLen + yLen * yLen);}float area(Point A, Point B, Point C){float a = side(B, C);float b = side(A, C);float c = side(A, B);float p = (a + b + c)/ 2;//海伦公式float s = sqrt(p * (p - a) * (p - b) * ( p - c));return s;}bool isEqual(float x, float y){if(fabs(x - y) < 0.0001)return true;return false;}int main(){Point A, B, C, P;    //可以对A进行整体赋值,下面采用的是分步赋值A.x = 0;A.y = 0;  // A(0, 0)B.x = 2;B.y = 0;  // B(2, 0)C.x = 1;C.y = 1;  // C(1, 1)P.x = 0.5;P.y = 0.6; // P(0.5, 0.6)float s  = area(A, B, C);float s1 = area(P, B, C);float s2 = area(P, A, C);float s3 = area(P, A, B);if(isEqual(s1 + s2 + s3, s) && !isEqual(s1, 0) && !isEqual(s2, 0) && !isEqual(s3, 0))cout << "Point P lies in the triangle ABC" << endl;elsecout << "Point P does not lie in the triangle ABC" << endl;return 0;}