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
如果我们在其中一个三角形上应用勾股定理,则
P2+(1/2)2=r2
P=√r2−(12/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:使用静态输入值
在这种方法中,我们在程序中初始化半径和弦长的值。然后,使用算法,我们可以找到圆心到弦的最短距离。
Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.
示例
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中找到圆心到弦的最短距离。