这一题的恶心之处在于直线L的A,B两点只是直线上普通的两点,我一开始把它错以为是与圆的交点。
我们应该通过前面某一题的方法求出点到直线的距离,然后再通过勾股定理,求出AB的距离,记得要乘二
import java.util.Scanner;
class Point {
double x, y;
Point(double A, double B) {
x = A;
y = B;
}
}
class Line {
Point point_A, point_B;
Line(Point A, Point B) {
point_A = A;
point_B = B;
}
}
class Circle {
Point O;
int r;
Circle(Point A, int B) {
O = A;
r = B;
}
}
public class Main {
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;
}
public static double getDistance(Circle circle, Line l) {
// 请在这里实现你的代码
double ao=distance(l.point_A, circle.O);
double ab=distance(l.point_A, l.point_B);
double ob=distance(circle.O, l.point_B);
double cosA=(ao*ao+ab*ab-ob*ob)/(2*ao*ab);
double sinA=Math.sqrt(1-cosA*cosA);
double d=ao*sinA;
if(d>=circle.r) {
return 0;
}
return 2*Math.sqrt(circle.r*circle.r-d*d);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double ox = scanner.nextDouble();
double oy = scanner.nextDouble();
int r = scanner.nextInt();
double x1 = scanner.nextDouble();
double y1 = scanner.nextDouble();
double x2 = scanner.nextDouble();
double y2 = scanner.nextDouble();
Point center = new Point(ox, oy);
Circle circle = new Circle(center, r);
Point p1 = new Point(x1, y1);
Point p2 = new Point(x2, y2);
Line l = new Line(p1, p2);
double result = getDistance(circle, l);
System.out.printf("%.6f\n", result);
scanner.close();
}
}



京公网安备 11010502036488号