**9.12(幾何:交點)假設兩條線段相交。第一條線段的兩個端點是(x1,y1)和(x2,y2),第二條線段的兩個端點是(x3,y3)和(x4,y4)。編寫一個程式,提示使用者輸入這四個端點,然後顯示他們的交點。如程式設計練習題3.25所討論的,可以通過對一個線性方程求解得到交點。使用程式設計練習題9.11中的LinearEquation來求解該方程。參見程式設計練習題3.25的執行示例。 **9.12(Geometry: Intersections)Suppose two lines intersect. The two endpoints of the first segment are (x1, Y1) and (X2, Y2), and the two endpoints of the second segment are (X3, Y3) and (x4, Y4). Write a program that prompts the user to enter these four endpoints, and then displays their intersections. As discussed in programming exercise 3.25, the intersection can be obtained by solving a linear equation. Use lineareequation in programming exercise 9.11 to solve the equation. See programming exercise 3.25 for an example.
參考程式碼:
package chapter09;import java.util.Scanner;publicclassCode_12{publicstaticvoidmain(String[] args){
Scanner cin =newScanner(System.in);double x1,y1,x2,y2,x3,y3,x4,y4;
System.out.print("Enter x1,y1,x2,y2,x3,y3,x4,y4:");
x1 = cin.nextDouble();
y1 = cin.nextDouble();
x2 = cin.nextDouble();
y2 = cin.nextDouble();
x3 = cin.nextDouble();
y3 = cin.nextDouble();
x4 = cin.nextDouble();
y4 = cin.nextDouble();double a,b,c,d,e,f;
a = y1 - y2;
b =-(x1 - x2);
c = y3 - y4;
d =-(x3 - x4);
e =(y1-y2)*x1 -(x1-x2)*y1;
f =(y3-y4)*x3 -(x3-x4)*y3;
LinearEquation expr =newLinearEquation(a,b,c,d,e,f);if(expr.isSolvable()){
System.out.println("x:"+ expr.getX()+" "+"y:"+ expr.getY());}else
System.out.println("The tow line are parallel");}}
結果顯示:
Enter x1,y1,x2,y2,x3,y3,x4,y4:225-1.04.02.0-1.0-2.0
x:2.888888888888889 y:1.1111111111111112
Process finished with exit code 0