您的位置:首页 > 其它

判断一个点是否在三角形内

2016-09-19 22:32 597 查看
平面上给定一个三角形ABC以及任意点P,判断点P是否是三角形内的点(点P在三角形边上也认为是在三角形内),输入的点坐标都是单精度浮点数。

实现原理参考:http://www.yalewoo.com/in_triangle_test.html

其实现代码如下:

#include <cstdio>
#include <iostream>
#include<vector>
using namespace std;
const float e = 0.000001;

struct Point{
float x;
float y;
Point(float a, float b) :x(a), y(b){ }
};

float cross(const Point &a, const Point &b, const Point &p)
{
return (b.x - a.x)*(p.y - a.y) - (b.y - a.y)*(p.x - a.x);
}

bool inTriangle(const Point &p, const Point &a, const Point &b, const Point &c)
{
if (cross(a, b, p) < 0 && cross(b, c, p) < 0 && cross(c, a, p) < 0)
return true;
if (cross(a, b, p) > 0 && cross(b, c, p) > 0 && cross(c, a, p) > 0)
return true;
if ((cross(a, b, p) - 0.0 > -e) && (cross(a, b, p) - 0.0 < e))
return true;
if ((cross(b, c, p) - 0.0 > -e) && (cross(b, c, p) - 0.0 < e))
return true;
if ((cross(c, a, p) - 0.0 > -e) && (cross(c, a, p) - 0.0 < e))
return true;
return false;
}

int main()
{
float x;
vector<float> vec;
for (int i = 0; i !=8; ++i)
{
cin >> x;
vec.push_back(x);
}
Point A(vec[0], vec[1]);
Point B(vec[2], vec[3]);
Point C(vec[4], vec[5]);
Point D(vec[6], vec[7]);

if (inTriangle(D, A, B, C))
cout <<"Yes"<<endl;
else
cout << "No"<<endl;
system("pause");
return 0;
}实验结果如下:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: