• 求两线段交点(Java)


    import java.util.Scanner;
    
    class point {
        double x, y;
    
        point(double x, double y) {
            this.x = x;
            this.y = y;
        }
    }
    
    class LinearEquation {
        point a, b, c, d;
        double x, y;
    
        LinearEquation(point a, point b, point c, point d) {
            this.a = a;
            this.b = b;
            this.c = c;
            this.d = d;
        }
    
        boolean solve() {
            double denominator = (b.y - a.y) * (d.x - c.x) - (a.x - b.x)
                    * (c.y - d.y);
            if (Math.abs(denominator) < 0.000001)
                return false;
            this.x = ((b.x - a.x) * (d.x - c.x) * (c.y - a.y) + (b.y - a.y)
                    * (d.x - c.x) * a.x - (d.y - c.y) * (b.x - a.x) * c.x)
                    / denominator;
            this.y = -((b.y - a.y) * (d.y - c.y) * (c.x - a.x) + (b.x - a.x)
                    * (d.y - c.y) * a.y - (d.x - c.x) * (b.y - a.y) * c.y)
                    / denominator;
            if ((x - a.x) * (x - b.x) <= 0 && (y - a.y) * (y - b.y) <= 0
                    && (x - c.x) * (x - d.x) <= 0 && (y - c.y) * (y - d.y) <= 0)
                return true;
            return false;
        }
    }
    
    public class Main {
    
        public static void main(String[] args) {
            Scanner cin = new Scanner(System.in);
            while (cin.hasNext()) {
                point p[] = new point[5];
                for (int i = 0; i < 4; i++) {
                    double x = cin.nextDouble();
                    double y = cin.nextDouble();
                    p[i] = new point(x, y);
                }
                LinearEquation ans = new LinearEquation(p[0], p[1], p[2], p[3]);
                if (ans.solve()) {
                    System.out.printf("The intersecting point is: (%.2f,%.2f)
    ",
                            ans.x, ans.y);
                } else
                    System.out.println("The two lines do not cross");
            }
        }
    
    }
  • 相关阅读:
    CSP-S全国模拟赛第三场 【nan死了】
    ●SCOI2018 AFO
    ●洛谷P2934 [USACO09JAN]安全出行Safe Travel
    ●洛谷P3233 [HNOI2014]世界树
    ●洛谷P2495 [SDOI2011]消耗战
    ●UOJ58 [WC2013]糖果公园
    ●洛谷P1903 [国家集训队]数颜色
    ●BZOJ 4237 稻草人
    ●Joyoi Normal
    ●CodeForces 698C LRU
  • 原文地址:https://www.cnblogs.com/zuferj115/p/5318740.html
Copyright © 2020-2023  润新知