点是否在三角形内C++源码实现

原理

思路:
面积和:
abc == obc+aoc+abo,应该有更简洁的方法,但是这个方法思路更简单
在这里插入图片描述

代码实现:

注意二维向量的叉乘后,是垂直于平面的向量,相当于z为0三维向量叉乘,所以只有z维度有值,xy=0.
float值不要直接==,考虑作差或者用库函数。

#include <string>
#include <math.h>

using namespace std;

struct Vec {
    float x_;
    float y_;

    Vec() {}

    float dot(const Vec &other) {
        return sqrt(x_ * x_ + y_ * y_);
    }

    float cross_norm(const Vec &other) {
        // Vec3d {y0*z1-z0-y1, -(x0*z1-z0*x1), x0*y1-x1*y0}
        float Vec3d_z = x_ * other.y_ - y_ * other.x_;
        return fabs(Vec3d_z);
    }
};

struct Point {
    float x_;
    float y_;

    Point() {}

    Point(const float &x, const float &y) : x_(x), y_(y) {}

    Vec operator-(const Point &other) const {
        Vec res;
        res.x_ = x_ - other.x_;
        res.y_ = y_ - other.y_;
        return res;
    }
};

struct Triangle {
    Point A_;
    Point B_;
    Point C_;

    Triangle(const Point &A, const Point &B, const Point &C) : A_(A), B_(B), C_(C) {}

    float get_area() const {
        Vec a = A_ - B_;
        Vec b = A_ - C_;
        return a.cross_norm(b) / 2;
    }
};

float get_area(const Triangle &tmp) {
    return tmp.get_area();
}


int main() {
    Point A(0.0, 0.0);
    Point B(1.0, 2.0);
    Point C(2.0, 1.0);
    Point O(1.5, 1.49);

    float area_ABC = get_area(Triangle(A, B, C));
    float area_OBC = get_area(Triangle(O, B, C));
    float area_AOC = get_area(Triangle(A, O, C));
    float area_ABO = get_area(Triangle(A, B, O));

    bool in_tri = fabs(area_ABC - (area_OBC + area_AOC + area_ABO)) < 0.0001; // notify : cannot float A == float B

    if (in_tri)
        printf("Point in Triangle");
    else
        printf("Point Not in Triangle");

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

知其所以然也

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值