本题最好不要用直线方程或线段夹角来判断,因为这涉及到分类与讨论,下面的算法是相对比较好的算法,代码如下:
#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;
else
cout << "Point P does not lie in the triangle ABC" << endl;
return 0;
}