Java、点是否在三角形内?

        假设一个平面上有一个三角形。编写程序,提示用户输入三角形的三个点,提示用户输入一个点的x坐标和y坐标,然后判断这个点是否在该三角形内。


package pack2;

import java.util.Scanner;

import javafx.geometry.Point2D;

public class InTriangle {

	public static void main(String[] args) {
		try(Scanner input = new Scanner(System.in);) {
			System.out.print("Enter three points of a triangle: ");
			double x0 = input.nextDouble(), y0 = input.nextDouble();
			double x1 = input.nextDouble(), y1 = input.nextDouble();
			double x2 = input.nextDouble(), y2 = input.nextDouble();
			
			System.out.print("Enter a point's x- and y-coordinates: ");
			System.out.println("The point is "+(isInTriangle(input.nextDouble(),     
         input.nextDouble(), x0, y0, x1, y1, x2, y2) ? "" : "not ")+"in the triangle");
		}
	}

	//判定是否在三角形内
	public static boolean isInTriangle(double x, double y, double x0, double y0,
         double x1, double y1, double x2, double y2) {
		//三角形的三个点
		Point2D p1 = new Point2D(x0, y0);	
		Point2D p2 = new Point2D(x1, y1);
		Point2D p3 = new Point2D(x2, y2);
		
		return Math.abs(getArea(p1, p2, p3) - (getArea(new Point2D(x, y), p2, p3) +     
     getArea(p1, new Point2D(x, y), p3) + getArea(p1, p2, new Point2D(x, y)))) < 0.00001;
	}
	
	//获取面积
	public static double getArea(Point2D p1, Point2D p2, Point2D p3) {
		double side1 = p1.distance(p3);
		double side2 = p1.distance(p2);
		double side3 = p2.distance(p3);
		double s = (side1 + side2 + side3) / 2;
		
		return Math.sqrt(s * (s - side1) * (s - side2) * (s - side3));
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值