import java.util.Scanner; public class Main { static class Point { double x, y; Point(double a, double b) { x = a; y = b; } } static class Line { Point pointA, pointB; Line(Point a, Point b) { pointA = a; pointB = b; } } static double distance(Point a,Point b) { double d=Math.sqrt(Math.pow(a.x-b.x, 2)+Math.pow(a.y-b.y, 2)); return d; } static double getDistance(Point P, Line L) { double pa=distance(P, L.pointA); double ab=distance(L.pointA, L.pointB); double pb=distance(P, L.pointB); double cosA=(pa*pa+ab*ab-pb*pb)/(2*pa*ab);//余弦定理 double sinA=Math.sqrt(1-cosA*cosA); return pa*sinA; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int a = scanner.nextInt(); int b = scanner.nextInt(); int sx = scanner.nextInt(); int sy = scanner.nextInt(); int tx = scanner.nextInt(); int ty = scanner.nextInt(); Point pointA = new Point(sx, sy); Point pointB = new Point(tx, ty); Point pointC = new Point(a, b); Line line = new Line(pointA, pointB); System.out.printf("%.2f", getDistance(pointC, line)); scanner.close(); } }
这道题主要是采用余弦定理的做法,来把点到直线距离求解