Java程式計算圓心到弦的最短距離


圓是一種二維的圓形圖形,沒有角。每個圓都有一個原點,圓上的每個點到原點的距離都相等。圓的原點到圓上任意一點的距離稱為圓的半徑。同樣,如果我們從圓的一端到另一端畫一條線,並且原點位於這條線的中點,那麼這條線稱為圓的直徑。基本上,直徑是半徑長度的兩倍。

圓的弦是指連線圓上兩個端點的線。或者簡單地說,弦是指端點位於圓上的線。弦將圓分成兩部分。

根據題意,我們需要找到圓心到圓的一條弦的最短距離。我們知道,垂直距離是最短距離。

因此,如果從圓心到弦的兩端分別畫兩條線,我們將得到一個三角形。垂直線將三角形分成兩個相等的部分。

Let the radius of circle = r
Length of the chord = l
So, if perpendicular line bisects the chords in two equal parts, then length of one equal part = l/2
Perpendicular line (bisector line) = p

如果我們在其中一個三角形上應用勾股定理,則

$$\mathrm{P^{2}+(1/2)^{2}=r^{2}}$$

$$\mathrm{P=\sqrt{r^{2}}-(1^{2}/4)}$$

因此,讓我們繼續看看如何使用Java程式語言找到圓心到弦的最短距離。

為了展示一些例項 -

例項1

Given radius (r) of the circle is 5
Length of the chord (l) is 4
Then the shortest distance from centre of the circle to the chord = sqrt((r * r) - ((l * l) / 4)) = sqrt((5 * 5) - ((4 * 4) / 4)) = 4.58.

例項2

Given radius (r) of the circle is 5.5.
Length of the chord (l) is 3.5
Then the shortest distance from centre of the circle to the chord = sqrt((r * r) - ((l * l) / 4)) = sqrt((4.5 * 4.5) - ((3.5 * 3.5) / 4)) = 4.14.

例項3

Given radius (r) of the circle is 6.
Length of the chord (l) is 4.
Then the shortest distance from centre of the circle to the chord = sqrt((r * r) - ((l * l) / 4)) = sqrt((6 * 6) - ((4 * 4) / 4)) = 5.65.

語法

為了獲取一個數的平方根,我們在java.lang包的Math類中有一個內建的sqrt()方法。

以下是使用該方法獲取任何數的平方根的語法。

double squareRoot = Math.sqrt(input_vale)

類似地,為了獲取Java中任何數的另一個數次冪,我們有內建的java.lang.Math.pow()方法。

以下是使用該方法獲取2的冪的語法 -

double power = Math.pow (inputValue,2)

演算法

步驟1 - 透過靜態輸入或使用者輸入獲取圓的半徑和絃的長度。

步驟2 - 使用公式找到圓心到弦的最短距離。

步驟3 - 列印結果。

多種方法

我們提供了不同方法的解決方案。

  • 使用靜態輸入值。

  • 使用使用者定義的方法。

讓我們逐一檢視程式及其輸出。

方法1:使用靜態輸入值

在這種方法中,我們在程式中初始化半徑和絃長的值。然後,使用演算法,我們可以找到圓心到弦的最短距離。

示例

public class Main {
   //main method
   public static void main(String[] args) {
      //radius of circle
      double r = 6;
      //length of chord
      double l = 4;
      //find shortest distance by using formula
      double distance = Math.sqrt((r * r) - ((l * l) / 4));
      System.out.println("The shortest distance: "+distance);
   }
}

輸出

The shortest distance: 5.656854249492381

方法2:使用帶有靜態輸入值的使用者定義方法。

在這種方法中,我們在程式中將半徑和絃長的值作為使用者輸入。然後,使用演算法,我們可以找到圓心到弦的最短距離。

示例

public class Main {
   //main method
   public static void main(String[] args) {
      double r = 6, l = 4;
      findShortestDistance(r, l);
   }
   //user defined method to find the shortest distance
   static void findShortestDistance(double r, double l) {
      //find shortest distance by using formula
      double distance = Math.sqrt((r * r) - ((l * l) / 4));
      System.out.println("The shortest distance: "+distance);
   }
}

輸出

The shortest distance: 5.656854249492381

在本文中,我們探討了如何使用不同的方法在Java中找到圓心到弦的最短距離。

更新於: 2022年12月27日

328次瀏覽

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告