class CalcArea { //点 public class Point { private double x; private double y; public Point(double a, double b) { x = a; y = b; } public double getX() { return x; } public double getY() { return y; } public void setX(double a) { x = a; } public void setY(double b) { y = b; } } //边 public class Line { private Point p1; private Point p2; public Line(Point x, Point y) { p1 = x; p2 = y; } public Point getP1() { return p1; } public Point getP2() { return p2; } public void setP1(Point x) { p1 = x; } public void setP2(Point x) { p2 = x; } } //三角形 public class Triangle { private Point p1; private Point p2; private Point p3; public Triangle(Point a, Point b, Point c) { p1 = a; p2 = b; p3 = c; } public Point getP1() { return p1; } public Point getP2() { return p2; } public Point getP3() { return p3; } public void setP1(Point x) { p1 = x; } public void setP2(Point x) { p2 = x; } public void setP3(Point x) { p3 = x; } } //计算三角形面积 public class Util { //计算两点间距离 public static double dispp(Point p1, Point p2) { double distX = p1.getX() - p2.getX(); double distY = p1.getY() - p2.getY(); return Math.Sqrt(distX * distX + distY * distY); } //点到直线的距离 public static double displ(Point p, Line l) { double lx1 = l.getP1().getX(); double lx2 = l.getP2().getX(); double ly1 = l.getP1().getY(); double ly2 = l.getP2().getY(); double k = (ly2 - ly1) / (lx2 - lx1); double b = ly1 - k * lx1; return Math.Abs((p.getY() - k * p.getX() - b)) / Math.Sqrt((k * k + 1)); } //计算面积 public static double triArea(Triangle t) { Line l = new Line(t.getP1(), t.getP2()); return Util.dispp(t.getP1(), t.getP2()) * Util.displ(t.getP3(), l) / 2; } //向量方法计算 public static double triArea1(Triangle t) { double area = 0; double a = Util.dispp(t.getP1(), t.getP2()); double b = Util.dispp(t.getP2(), t.getP3()); double c = Util.dispp(t.getP1(), t.getP3()); double d = (a + b + c) / 2; area = Math.Sqrt(d * (d - a) * (d - b) * (d - c)); return area; } } }
#region testTriangle /// <summary> /// 计算点在不在三角形内部 /// </summary> private void testTriangle() { CalcArea.Point p1 = new CalcArea.Point(-1, 1); CalcArea.Point p2 = new CalcArea.Point(1, 0.5); CalcArea.Point p3 = new CalcArea.Point(2, -3); double x = 0.8; double y = 0.3; CalcArea.Point p4 = new CalcArea.Point(x, y); CalcArea.Triangle t; t = new CalcArea.Triangle(p1, p2, p3); double sourceArea = Convert.ToDouble(CalcArea.Util.triArea(t)); t = new CalcArea.Triangle(p1, p2, p4); double area1 = Convert.ToDouble(CalcArea.Util.triArea1(t)); t = new CalcArea.Triangle(p3, p2, p4); double area2 = Convert.ToDouble(CalcArea.Util.triArea1(t)); t = new CalcArea.Triangle(p1, p3, p4); double area3 = Convert.ToDouble(CalcArea.Util.triArea1(t)); if (sourceArea == (double)((int)((area1 + area2 + area3) * 100)) / 100) { Console.WriteLine("点在三角形内部!"); } else { Console.WriteLine("点不在三角形内部!"); } Console.ReadLine(); } #endregion
时间: 2024-11-10 05:29:13