判断一个点是否在三个点组成的三角形内 java 代码 面试经典

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

class Point {
    int x;
    int y;

    Point(int x, int y) {
        this.x = x;
        this.y = y;
    }
}

public class pointInTrangle {
    public static void main(String[] args) {
        Point p1 = null;
        Point p2 = null;
        Point p3 = null;
        Point p = null;
        System.out.println("请输入四个点");
        System.out.println("第一个点");
        p1 = input();
        System.out.println("第二个点");
        p2 = input();
        System.out.println("第三个点");
        p3 = input();
        System.out.println("第四个点");
        p = input();
        System.out.println(panduan(p1, p2, p3, p) ? "在三角形内" : "不在三角形内");
    }

    public static boolean panduan(Point a, Point b, Point c, Point p) {
        double abc = triangleArea(a, b, c);
        double abp = triangleArea(a, b, p);
        double acp = triangleArea(a, c, p);
        double bcp = triangleArea(b, c, p);
        if (abc == abp + acp + bcp) {
            return true;
        } else {
            return false;
        }
    }

    private static double triangleArea(Point a, Point b, Point c) {// 返回三个点组成三角形的面积
        double result = Math.abs((a.x * b.y + b.x * c.y + c.x * a.y - b.x * a.y
                - c.x * b.y - a.x * c.y) / 2.0D);
        return result;
    }

    private static Point input() {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int a = 0, b = 0;
        try {
            a = Integer.parseInt(br.readLine());
            b = Integer.parseInt(br.readLine());
        } catch (NumberFormatException e) {
            e.printStackTrace();
        } catch (IOException e) {             e.printStackTrace();         }
        return new Point(a, b);     } }

posted @ 2015-10-14 21:07  剑芒  阅读(749)  评论(0编辑  收藏  举报