第八章第十五题(几何:在一条直线上吗?)(Geometry: on a straight line?)

第八章第十五题(几何:在一条直线上吗?)(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
    
    
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值