首页 > 文章列表 > 如何在Java中找到一条线的中点?

如何在Java中找到一条线的中点?

java 中点 线
424 2023-08-27

假设(x1,y1)是线的起点,(x2,y2)是线的终点。

要获得直线的中点,我们必须使用直线的中点公式。

Midpoint = ((x1+x2)/2 , (y1+y2)/2)

在本文中,我们将看到如何使用Java编程语言找到线段的中点,当线段的两个点已知时。

展示给你一些实例

实例1

假设这两个点是(2,3)和(3,5)

通过使用线段的中点公式,

a = (x1+x2)/2 = (2+3)/2 = 2.5
b = (y1+y2)/2 = (3+5)/2 = 4.0

因此,直线的中点是 (2.5, 4.0)

实例2

假设这两个点是(2,-3)和(-3,5)

通过使用线段的中点公式,

a = (x1+x2)/2 = (2+(-3)/2 = -0.5
b = (y1+y2)/2 = ((-3) +5)/2 = 1.0

因此,线段的中点为 (-0.5, 1.0)

实例3

假设这两个点是 (2,2) 和 (5,5)

通过使用线段的中点公式,

a = (x1+x2)/2 = (2+5)/2 = 3.5
b = (y1+y2)/2 = (2+5)/2 = 3.5

因此,线段的中点是(3.5,3.5)

算法

  • 第 1 步 - 通过静态输入或用户输入获取直线的起点和终点。

  • 第二步 - 然后通过使用线段的中点公式找到中点。

  • 第 3 步 - 打印结果。

多种方法

我们已经以不同的方法提供了解决方案。

  • 通过使用静态输入值

  • 通过使用用户定义的方法

让我们一一看看该程序及其输出。

方法 1:使用静态输入值

在这种方法中,线的起点和终点将在程序中初始化。然后利用算法找到思维点。

Example

的中文翻译为:

示例

public class Main{
   //main method
   public static void main(String[] args){
   
      //declared start point of line
      double x1 = -3;
      double y1 = 4;
      System.out.println("Start point of the line: "+x1+", "+y1);
      
      //Declared end point of line
      double x2 = -2;
      double y2 = 5;
      System.out.println("End point of the line: "+x2+", "+y2);
      
      //Find midpoint
      double x=(x1+x2)/2;
      double y=(y1+y2)/2;
      System.out.println("Mid Point = "+x+" , "+y);
   }   
}

输出

Start point of the line: -3.0, 4.0
End point of the line: -2.0, 5.0
Mid Point = -2.5 , 4.5

方法 2:使用用户定义

在这种方法中,线的起点和终点将在程序中初始化。然后通过将这些点作为参数传递来调用用户定义的方法,并在方法内部使用算法找到中点。

Example

的中文翻译为:

示例

public class Main{
   //main method
   public static void main(String[] args){
   
      //declared start point of line
      double x1 = 2;
      double y1 = 2;
      System.out.println("Start point of the line: "+x1+", "+y1);
      
      //Declared end point of line
      double x2 = 7;
      double y2 = 9;
      System.out.println("End point of the line: "+x2+", "+y2);

      //call user defined method to find midpoint
      findMidpoint(x1,y1,x2,y2);
   }
   //user defined method
   public static void findMidpoint(double x1,double y1,double x2,double y2){
      //Find midpoint
      double x=(x1+x2)/2;
      double y=(y1+y2)/2;
      System.out.println("Mid Point = "+x+" , "+y);
   }
}

输出

Start point of the line: 2.0, 2.0
End point of the line: 7.0, 9.0
Mid Point = 4.5 , 5.5

在本文中,我们探讨了如何使用不同的方法在 Java 中找到直线的中点。