2016-09-22 59 views
0

因此,我需要編寫一個程序來決定一條線是否攔截一個圓。不需要特定的攔截座標,只需觸摸圓或與其相切即可攔截。如果之前已經問過這個問題,我很抱歉,但是我找不到適合我的問題的東西。也許我看起來不夠堅硬。(java)決定一條線是否攔截一個圓

import java.util.Scanner; 
public class LineCircle_Intersection { 

public static void main(String[] args) { 
    Scanner in = new Scanner(System.in); 

    double p1x, p2x, p1y, p2y, cx, cy, r; 

    System.out.print("Enter p1x: "); 
    p1x = in.nextDouble(); 
    System.out.print("Enter p1y: "); 
    p1y = in.nextDouble(); 
    System.out.print("Enter p2x: "); 
    p2x = in.nextDouble(); 
    System.out.print("Enter p2y: "); 
    p2y = in.nextDouble(); 
    System.out.print("Enter cx: "); 
    cx = in.nextDouble(); 
    System.out.print("Enter cy: "); 
    cy = in.nextDouble(); 
    System.out.print("Enter r: "); 
    r = in.nextDouble(); 

    if ((p1x - cx < r) && (p1y - cy < r)) 
     System.out.println("The line intersects the circle."); 
    else if ((p2x - cx < r) && (p2y - cy < r)) 
     System.out.println("The line intersects the circle."); 
    else 
     System.out.println("The line does not intersect the circle."); 

} 

} 

我一直在使用直線和圓的公式而不是輸入點的替代路線,但它是一種亂七八糟的,我不知道在哪裏,我用它去。

+0

這應該有助於https://en.wikipedia.org/wiki/Distance_from_a_point_to_a_line – BevynQ

回答

0

我們可以寫爲線爲y-P1Y = M(X-P1X),其中,m =(P2Y-P1Y)/(P2X-P1X)

則y = M(X-P1X方程)+ P1Y(1)

我們可以寫出方程式圓爲(x-CX)^ 2 +(Y-CY)^ 2 = R^2(2)

如果我們plug (1) into (2)我們得到:

x^2(1 + m)+ x(-2a + 2cm-2dm-2bm)+ a^2-2cmb + 2dmb + mb^2 + c^2-2cd + d^2-r^2 = 0

其中

A = CX

B = P1X

C = P1Y

d = CY

A」 =(1 + M)

b'=( - 2a + 2cm-2dm-2bm)

C」 = A^2-2cmb + 2dmb + MB^2 + C^2-2cd + d^2-R^2

我們然後知道,線和circurfence如果

彼此接觸

b'^ 2-4a'c'> = 0