Java程式查詢圓的最長弦
圓是一個沒有角的二維圓形圖形。每個圓都有一個原點,圓上的每個點與原點保持相等的距離。原點與圓上一點之間的距離稱為圓的半徑。同樣,如果我們從圓的一邊到另一邊畫一條線,並且原點位於它的中間,那麼這條線稱為圓的直徑。基本上,直徑是半徑長度的兩倍。
圓的弦指的是從圓的一個端點到另一個端點的線。或者簡單地說,弦指的是端點位於圓上的線。弦將圓分成兩部分。
根據題意,我們需要找到圓的最長弦。很明顯,穿過原點的線是最長弦,它就是直徑。
如果給出半徑 (r),則圓的直徑為 2r。
因此,圓的最長弦為 2r。所以,讓我們繼續看看如何使用 Java 程式語言找到圓的最長弦。
舉幾個例子:
示例 1
Given radius (r) of the circle is 5 Then the longest chord of the circle = 2r = 2 * 5 = 10
示例 2
Given radius (r) of the circle is 4.5 Then the longest chord of the circle = 2r = 2 * 4.5 = 9
示例 3
Given radius (r) of the circle is 4 Then the longest chord of the circle = 2r = 2 * 4 = 8
演算法
步驟 1 - 透過靜態輸入或使用者輸入獲取圓的半徑。
步驟 2 - 找到圓的直徑,它也就是圓的最長弦。
步驟 3 - 列印結果。
多種方法
我們提供了不同方法的解決方案。
使用靜態輸入值。
使用帶有靜態輸入值的使用者定義方法。
使用帶有使用者輸入值的使用者定義方法。
讓我們逐一檢視程式及其輸出。
方法 1:使用靜態輸入值
在這種方法中,我們宣告一個雙精度變數並用圓的半徑值初始化它。然後,使用演算法我們可以找到圓的最長弦。
示例
import java.util.*;
public class Main {
//main method
public static void main(String[] args) {
// radius of the circle
double r = 7;
//find the longest chord i.e diameter
double chord=2*r;
//print result
System.out.println("Length of longest chord of the circle:"+chord);
}
}
輸出
Length of longest chord of the circle: 14.0
方法 2:使用帶有靜態輸入值的使用者定義方法
在這種方法中,我們宣告一個雙精度變數並用圓的半徑值初始化它。透過將此半徑值作為引數呼叫使用者定義的方法。然後在方法內部使用演算法找到圓的最長弦。
示例
public class Main {
//main method
public static void main(String[] args) {
//radius of the circle
double r = 4;
//call the user defined method to find longest chord
findLongestChord(r);
}
//user defined method to find longest chord
static void findLongestChord(double r) {
//find the longest chord i.e diameter
double chord=2*r;
//print result
System.out.println("Longest chord of the circle: "+chord);
}
}
輸出
Longest chord of the circle: 8.0
方法 3:使用帶有使用者輸入值的使用者定義方法
在這種方法中,我們宣告一個雙精度變數並獲取圓的半徑值的使用者輸入。透過將此半徑值作為引數呼叫使用者定義的方法。然後在方法內部使用演算法找到圓的最長弦。
示例
import java.util.*;
public class Main {
//main method
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter radius of circle: ");
//take user inout of radius of the circle
double r = sc.nextDouble();
//call the user defined method to find longest chord
findLongestChord(r);
}
//user defined method to find longest chord
static void findLongestChord(double r) {
//find the longest chord i.e diameter
double chord=2*r;
//print result
System.out.println("Length of longest chord of the circle: "+chord);
}
}
輸出
Enter radius of circle: 4.5 Length of longest chord of the circle: 9.0
在本文中,我們探討了如何使用不同的方法在 Java 中找到圓的最長弦。
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP