检查给定的点是否在三角形内\n
给定三角形的三个点;另外给定一个点 P 来检查点 P 是否在三角形内。
为了解决这个问题,不妨考虑三角形的点是 A、B 和 C。当三角形 Δ𝐴𝐵𝐶 的面积 = Δ𝐴𝐵𝑃 + Δ𝑃𝐵𝐶 + Δ𝐴𝑃𝐶 时,则点 P 在三角形内。
输入和输出
Input: Points of the triangle {(0, 0), (20, 0), (10, 30)} and point p (10, 15) to check. Output: Point is inside the triangle.
算法
isInside(p1, p2, p3, p)
输入:三角形的三个点,待检查的点 p。
输出:当 p 在三角形内时,返回 True。
Begin area := area of triangle(p1, p2, p3) area1 := area of triangle(p, p2, p3) area2 := area of triangle(p1, p, p3) area3 := area of triangle(p1, p2, p) if area = (area1 + area2 + area3), then return true else return false End
示例
#include <iostream> #include<cmath> using namespace std; struct Point { int x, y; }; float triangleArea(Point p1, Point p2, Point p3) { //find area of triangle formed by p1, p2 and p3 return abs((p1.x*(p2.y-p3.y) + p2.x*(p3.y-p1.y)+ p3.x*(p1.yp2.y))/2.0); } bool isInside(Point p1, Point p2, Point p3, Point p) { //check whether p is inside or outside float area = triangleArea (p1, p2, p3); //area of triangle ABC float area1 = triangleArea (p, p2, p3); //area of PBC float area2 = triangleArea (p1, p, p3); //area of APC float area3 = triangleArea (p1, p2, p); //area of ABP return (area == area1 + area2 + area3); //when three triangles are forming the whole triangle } int main() { Point p1={0, 0}, p2={20, 0}, p3={10, 30}; Point p = {10, 15}; if (isInside(p1, p2, p3, p)) cout << "Point is inside the triangle."; else cout << "Point is not inside the triangle"; }
输出
Point is inside the triangle.
广告