判断一个点是否在三个点组成的三角形内 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 @   剑芒  阅读(764)  评论(0编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~
点击右上角即可分享
微信分享提示