C++判断点是否在三角形内部

1.问题

  判断点是否在三角形内部。

2.思路

  计算向量AB和AP的叉积、向量BC和BP的叉积、向量CA和CP的叉积,如果所有的叉积符号相同,则点在三角形内部。
在这里插入图片描述

3.代码实现和注释

#include <iostream>
#include <vector>

// 计算两个二维向量的叉积
double crossProduct(const std::vector<double>& v1, const std::vector<double>& v2) {
  return v1[0] * v2[1] - v1[1] * v2[0];
}

// 判断点P是否在三角形ABC内部
bool isPointInsideTriangle(
  double ax, double ay,
  double bx, double by,
  double cx, double cy,
  double px, double py) {
  // 将点和顶点表示为向量
  std::vector<double> AB = {bx - ax, by - ay};
  std::vector<double> AP = {px - ax, py - ay};

  std::vector<double> BC = {cx - bx, cy - by};
  std::vector<double> BP = {px - bx, py - by};

  std::vector<double> CA = {ax - cx, ay - cy};
  std::vector<double> CP = {px - cx, py - cy};

  // 计算叉积
  int count1 = 0, count2 = 0;
  if (crossProduct(AB, AP) > 0)
    count1++;
  else
    count2++;

  if (crossProduct(BC, BP) > 0)
    count1++;
  else
    count2++;

  if (crossProduct(CA, CP) > 0)
    count1++;
  else
    count2++;

  // 如果计数为3,点在三角形内部
  printf("count1 = %d, count2 = %d\n", count1, count2);
  return count1 == 3 || count2 == 3;
}

int main() {
  double ax, ay, bx, by, cx, cy, px, py;
  std::cout << "Enter triangle vertices (A(x, y), B(x, y), C(x, y)):\n";
  std::cin >> ax >> ay >> bx >> by >> cx >> cy;
  std::cout << "Enter point P(x, y):\n";
  std::cin >> px >> py;

  bool result = isPointInsideTriangle(ax, ay, bx, by, cx, cy, px, py);
  if (result)
    std::cout << "Point P is inside the triangle.\n";
  else
    std::cout << "Point P is outside the triangle or on its boundary.\n";

    return 0;
}

相关推荐

  1. 判断是否一直线上

    2024-03-28 08:30:04       22 阅读
  2. 【POSTGIS】判定是否范围内

    2024-03-28 08:30:04       34 阅读
  3. C语言】等边等腰三角形判断

    2024-03-28 08:30:04       21 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-03-28 08:30:04       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-03-28 08:30:04       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-03-28 08:30:04       19 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-03-28 08:30:04       20 阅读

热门阅读

  1. 菜鸟笔记-15arange函数学习

    2024-03-28 08:30:04       15 阅读
  2. 代码随想录学习Day 19

    2024-03-28 08:30:04       17 阅读
  3. leetcode 2580.统计将重叠区间合并成组的方案数

    2024-03-28 08:30:04       16 阅读
  4. 大数据分布式事务的深入理解?

    2024-03-28 08:30:04       18 阅读
  5. Android Studio项目加载预编好的so库

    2024-03-28 08:30:04       21 阅读
  6. Vim - 文本编辑器 Vi vs Vim

    2024-03-28 08:30:04       22 阅读
  7. vim中如何使用Vundle插件管理器?

    2024-03-28 08:30:04       19 阅读
  8. GRE实验

    GRE实验

    2024-03-28 08:30:04      15 阅读
  9. Matlab将日尺度数据转化为月尺度数据

    2024-03-28 08:30:04       17 阅读
  10. 婚恋网站如何抵御DDoS攻击

    2024-03-28 08:30:04       18 阅读
  11. 云贝教育 |【技术文章】postgresql触发OOM解析

    2024-03-28 08:30:04       16 阅读
  12. 高频SQL 产品销售分析 I

    2024-03-28 08:30:04       17 阅读
  13. Pytorch多机多卡分布式训练

    2024-03-28 08:30:04       17 阅读
  14. 微信小程序修改checkbox和radio的样式

    2024-03-28 08:30:04       22 阅读
  15. Swift xcode app自动化

    2024-03-28 08:30:04       20 阅读