第九章第十二题(几何:交点)(Geometry: Intersections)

第九章第十二题(几何:交点)(Geometry: Intersections)

  • **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;

public class Code_12 {
    public static void main(String[] args){
        Scanner cin = new Scanner(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 = new LinearEquation(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:2 2 5 -1.0 4.0 2.0 -1.0 -2.0
x:2.888888888888889  y:1.1111111111111112

Process finished with exit code 0

©️2020 CSDN 皮肤主题: 点我我会动 设计师:上身试试 返回首页