第八章第十五题(几何:在一条直线上吗?)(Geometry: on a straight line?)
-
*8.15(几何:在一条直线上吗?)编程练习题6.39给出了一个方法,用于测试三个点是都在一条直线上。编写下面的方法,检测points数组中所有的点是否都在同一条直线上。
public static boolean sameLine(double[][] points)
编写一个程序,提示用户输入5个点,并且侠士他们是否在同一条直线上。下面是一个运行示例:
Enter five points:3.4 2 6.5 9.5 2.3 2.3 5.5 5 -5 4
The five points are not on the same line
Enter five points:1 1 2 2 3 3 4 4 5 5
The five points are on the same line
*8.15(Geometry: on a straight line?)Programming exercise 6.39 gives a method to test that all three points are on a straight line. Write the following method to detect whether all the points in the points array are on the same line.
public static boolean sameLine(double[][] points)
Write a program that prompts the user to enter 5 points and whether they are in the same line. Here is a running example:
Enter five points:3.4 2 6.5 9.5 2.3 2.3 5.5 5 -5 4
The five points are not on the same line
Enter five points:1 1 2 2 3 3 4 4 5 5
The five points are on the same line -
参考代码:
package chapter08; import java.util.Scanner; public class Code_15 { public static void main(String[] args) { Scanner input=new Scanner(System.in); System.out.print("Enter five points:"); double[][] points=new double[5][2]; for(int i=0;i<points.length;i++){ for(int j=0;j<points[i].length;j++){ points[i][j]=input.nextDouble(); } } if (sameLine(points)) System.out.println("The five points are on the same line"); else System.out.println("The five points are not on the same line"); } public static boolean sameLine(double[][] points){ double[] sentinel=new double[2]; sentinel[0]=points[0][0]; sentinel[1]=points[0][1]; for(int i=1;i<points.length;i++) { for (int j=1;j<points[i].length;j++) { double just=(points[i][j-1]-sentinel[0])*(points[i-1][j]-sentinel[1])-(points[i][j]-sentinel[0])*(points[i-1][j-1]-sentinel[1]); if (just!=0){ return false; } } } return true; } }
-
结果显示:
Enter five points:1 1 2 2 3 3 4 4 5 5 The five points are on the same line Process finished with exit code 0