编写一个方法,返回两条直线的交点。 方法头是:public static double[] getIntersectingPoint(double[][] points)

题目:
编写一个方法,返回两条直线的交点。
方法头是:public static double[] getIntersectingPoint(double[][] points)第一条直线上面的两个点是(x1,y1)和(x2,y2),第二条直线上面的两个点是(x3,y3)和(x4,y4),这些点保存在一个4 x 2的二维矩阵points中,其中(points[0][0],points[0][1])代表(x1,y1)。
方法返回交点,或者如果两条线平行的话就返回null。
编写一个程序,提示用户输入四个点,并且显示交点。

源代码如下:
package com;
import java.util.Arrays;
import java.util.Scanner;
public class test {
public static void main(String[] args) {
System.out.println(“请输入4个坐标的值:”);
double[][] points = new double[4][2];
Scanner in = new Scanner(System.in);
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 2; j++) {
points[i][j] = in.nextInt();
}
}
double array[]=getIntersectingPoint(points);
System.out.print(“交点是:(”);
for(int i=0;i<2;i++) {
if (i == 1) {
System.out.print(array[i] + ") ");
} else {
System.out.print(array[i] + “,”);
}
}
}
public static double[] getIntersectingPoint(double[][] points){
double x1 = points[0][0];
double y1 = points[0][1];
double x2 = points[1][0];
double y2 = points[1][1];
double x3 = points[2][0];
double y3 = points[2][1];
double x4 = points[3][0];
double y4 = points[3][1];
double K1 = (points[1][1] - points[0][1]) / (points[1][0] - points[0][0]);
double K2 = (points[3][1] - points[2][1]) / (points[3][0] - points[2][0]);
double[] arr=new double[2];
if (K1 != K2) {
double B1 = y1 - K1 * x1;
double B2 = y3 - K2 * x3;
arr[0]= (B2 - B1) / (K1 - K2);
arr[1]= (B2 * K1 - B1 * K2) / (K1 - K2);
} else {
System.out.println(“NULL”);
}
return arr;
}
}

主要就是找出交点的算法就可以了。
此文为原创,转载请注明出处。
如对你有帮助,请给我一个赞!

发布了9 篇原创文章 · 获赞 9 · 访问量 2162

猜你喜欢

转载自blog.csdn.net/grandniu/article/details/105617432