题目
题目描述
*8.31(几何:交点)编写一个方法,返回两条直线的交点。
假设(x1,y1)和(x2,y2)在直线1上,(x3,y3)和(x4,y4)在直线2上
方法头为:
public static double[] getIntersectingPoint(double[][] points)
四个点存放在4*2的二维数组points中,方法返回交点或null(平行)
编写一个程序,提示用户输入4个点,并显示交点
课本提示:
两条直线的交点可以使用编程练习题3.25(点击直达)的公式求得
ax+by=e
cx+dy=f
x = (e * d - b * f) / (a * d - b * c)
y = (a * f - e * c) / (a * d - b * c)
运行示例也要参见3.25
破题
- 主方法:声明一个4*2的二维数组
- 主方法:输出提示用户赋值的语句,并使用循环接收值
- 主方法:声明一个长度为2的一维数组
- 主方法:调用方法getIntersectingPoint,使用刚刚声明的一维数组接收方法返回值
- 主方法:输出坐标,以如下格式输出:The intersecting point is at (2.88889, 1,1111)
- 方法getIntersectingPoint:创建如下6个double数字a b c d e f,b和d初始值设置为1(a=-k1 b=1 c=-k2 d=1 e=b1 f=b2 )
- 方法getIntersectingPoint:对数组四个元素进行遍历,计算两个直线的斜率与截距(分别赋值给-a -c e f)
- 方法getIntersectingPoint:声明一个一维数组,长度为2
- 方法getIntersectingPoint:使用公式求出交点坐标,如果无法求出则强制退出并输出The two lines are parallel,如果求出则赋值给刚刚声明的一维数组
- 方法getIntersectingPoint:返回交点坐标数组
代码
import java.util.Scanner;
public class Test8_31 {
public static void main(String[] args) {
//1. 主方法:声明一个4*2的二维数组
double[][] array = new double[4][2];
//2. 主方法:输出提示用户赋值的语句,并使用循环接收值
Scanner input = new Scanner(System.in);
System.out.println("Enter x1, y1, x2, y2, x3, y3, x4, y4: ");
for (int i = 0 ; i < 4 ; i++){
for (int j = 0 ; j < 2 ;j++){
array[i][j] = input.nextDouble();
}
}
//3. 主方法:声明一个长度为2的一维数组
double[] intersection = new double[2];
//4. 主方法:调用方法getIntersectingPoint,使用刚刚声明的一维数组接收方法返回值
intersection = getIntersectingPoint(array);
//5. 主方法:输出坐标,以如下格式输出:The intersecting point is at (2.88889, 1,1111)
System.out.println("The intersecting point is at (" + intersection[0] + ", " + intersection[1] + ")");
}
public static double[] getIntersectingPoint(double[][] points){
//6. 方法getIntersectingPoint:创建如下6个double数字a b c d e f,b和d初始值设置为1
// a=-k1 b=1 c=-k2 d=1 e=b1 f=b2
double a, c, e, f, b=1, d=1;
//7. 方法getIntersectingPoint:对数组四个元素进行遍历,计算两个直线的斜率与截距
// (分别赋值给-a -c e f)
a = - (points[1][1] - points[0][1]) / (points[1][0] - points[0][0]);
c = - (points[3][1] - points[2][1]) / (points[3][0] - points[2][0]);
e = points[0][1] + a * points[0][0];
f = points[2][1] + c * points[2][0];
//8. 方法getIntersectingPoint:声明一个一维数组,长度为2
double[] center = new double[2];
//9. 方法getIntersectingPoint:使用公式求出交点坐标,如果无法求出则强制退出并输出,如果求出则赋值给刚刚声明的一维数组
if (a == c){
System.out.println("The two lines are parallel");
System.exit(1);
}
center[0] = (e * d - b * f) / (a * d - b * c);
center[1] = (a * f - e * c) / (a * d - b * c);
//10. 方法getIntersectingPoint:返回交点坐标数组
return center;
}
}
本题运行实例
Enter x1, y1, x2, y2, x3, y3, x4, y4:
2 2 5 -1.0 4.0 2.0 -1.0 -2.0
The intersecting point is at (2.888888888888889, 1.1111111111111112)