点在三角行

参考博客

算法1

利用面积法,如上图所示,如果点P在三角形ABC的内部,则三个小三角形PAB, PBC, PAC的面积之和 = ABC的面积,反之则不相等。

已知三角形的三个顶点坐标求其面积,可以根据向量的叉乘,参考。

2,3戳原链接

算法4

该算法和算法2类似,可以看作是对算法2的简化,也是用到向量的叉乘。假设三角形的三个点按照顺时针(或者逆时针)顺序是A,B,C。对于某一点P,求出三个向量PA,PB,PC, 然后计算以下三个叉乘(^表示叉乘符号):

t1 = PA^PB,

t2 = PB^PC,

t3 = PC^PA,

如果t1,t2,t3同号(同正或同负),那么P在三角形内部,否则在外部。

#include <iostream>
#include <bits/stdc++.h>
using namespace std;
struct point{
    double x;
    double y;
};
struct v{
    point s;
    point e;
};
struct triangle{
    point A;
    point B;
    point C;
};
double cross(v v1,v v2){
    double res=0;
    v vt1,vt2;
    vt1.s.x=0;
    vt1.s.y=0;
    vt1.e.x=v1.e.x-v1.s.x;
    vt1.e.y=v1.e.y-v1.s.y;
    vt2.s.x=0;
    vt2.s.y=0;
    vt2.e.x=v2.e.x-v2.s.x;
    vt2.e.y=v2.e.y-v2.s.y;
    res=vt1.e.x*vt2.e.y-vt1.e.y*vt2.e.x;
    return res;
}
bool inTriangle(triangle a,point P){
    v AB,AC,PA,PB,PC;
    AB.s=a.A;
    AB.e=a.B;
    AC.s=a.A;
    AC.e=a.C;
    PA.s=P;
    PA.e=a.A;
    PB.s=P;
    PB.e=a.B;
    PC.s=P;
    PC.e=a.C;
    double pab=cross(PA,PB);
    double pac=cross(PC,PA);
    double pbc=cross(PB,PC);
    if(pab*pac>=0&&pac*pbc>=0) return true;
    return false;
}
int main()
{
    point a,b,c,d;
    cin>>a.x>>a.y;
    cin>>b.x>>b.y;
    cin>>c.x>>c.y;
    cin>>d.x>>d.y;
    triangle xxx;
    xxx.A=a;
    xxx.B=b;
    xxx.C=c;
    if(inTriangle(xxx,d)==true) printf("in\n");
    else printf("out\n");
    return 0;
}

 

posted on   湫叶  阅读(121)  评论(0编辑  收藏  举报

编辑推荐:
· 对象命名为何需要避免'-er'和'-or'后缀
· SQL Server如何跟踪自动统计信息更新?
· AI与.NET技术实操系列:使用Catalyst进行自然语言处理
· 分享一个我遇到过的“量子力学”级别的BUG。
· Linux系列:如何调试 malloc 的底层源码
阅读排行:
· C# 中比较实用的关键字,基础高频面试题!
· .NET 10 Preview 2 增强了 Blazor 和.NET MAUI
· Ollama系列05:Ollama API 使用指南
· 为什么AI教师难以实现
· 如何让低于1B参数的小型语言模型实现 100% 的准确率
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示