随笔-19  评论-1  文章-0  trackbacks-0
 1.  一种是用矢量叉乘法:
        由三个顶点向所求的点引出矢量(注意方向),然后任意用其中两个矢量形成平面,再用这个平面和剩下的矢量叉乘,得出一个新矢量,方向向里,则在三角形外,反之在里面。
2.用面积方法

#include<stdio.h>
#include
<math.h>
struct TPoint {
    
float x;
    
float y;
}
;

//求叉积
float mul(struct TPoint p1, struct TPoint p2, struct TPoint p0) {
    
return ((p1.x - p0.x)*(p2.y - p0.y)-(p2.x - p0.x)*(p1.y - p0.y));
}

/*由三个顶点向所求的点引出矢量(注意方向),然后任意用其中两个矢量形成平面,
 * 再用这个平面和剩下的矢量叉乘,得出一个新矢量,方向向里,则在三角形外,反之在里面。
 
*/

int inside(struct TPoint tr[], struct TPoint p) {
    
int i;
    
for (i = 0; i < 3; i++)
        
if (mul(p, tr[i], tr[(i + 1% 3]) * mul(p, tr[(i + 2% 3], tr[(i + 1% 3]) > 0)
            
return 0;
    
return 1;
}


float area(struct TPoint p1, struct TPoint p2, struct TPoint p3) {
    
return fabs((p1.x - p3.x)*(p2.y - p3.y)-(p2.x - p3.x)*(p1.y - p3.y));
}

//用面积判断p是否在三角形内
int inside2(struct TPoint tr[], struct TPoint p) {
    
if (fabs(area(tr[0], tr[1], tr[2]) -
            area(p, tr[
1], tr[2]) -
            area(tr[
0], p, tr[2]) -
            area(tr[
0], tr[1], p)) < 1.0e-20)
        
return 1;
    
else
        
return 0;
}


int main() {
    
struct TPoint tr[3= {{-11},{10},{30}},  p = {12};

    
//方法一
    printf("algorithm   1:");
    
if (inside(tr, p))
        printf(
"In\n");
    
else
        printf(
"Out\n");

    
//方法一
    printf("algorithm   2:");
    
if (inside2(tr, p))
        printf(
"In\n");
    
else
        printf(
"Out\n");
}
posted on 2010-10-12 09:40 孟起 阅读(1576) 评论(0)  编辑 收藏 引用 所属分类: 计算几何

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理