如何在Java中找到直線的重點?
假設(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 - 透過靜態輸入或使用者輸入獲取直線的起點和終點。
步驟2 - 然後使用直線的重點公式找到重點。
步驟3 - 列印結果。
多種方法
我們提供了不同的方法來解決這個問題。
使用靜態輸入值
使用使用者自定義方法
讓我們逐一檢視程式及其輸出。
方法1:使用靜態輸入值
在這種方法中,直線的起點和終點將在程式中初始化。然後使用演算法找到重點。
示例
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:使用使用者自定義方法
在這種方法中,直線的起點和終點將在程式中初始化。然後透過將這些點作為引數傳遞來呼叫使用者自定義方法,並在方法內部使用演算法找到重點。
示例
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中找到直線的重點。
廣告
資料結構
網路
關係資料庫管理系統(RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP