在JAVA中,我們可以通過給定圓上的三個點(diǎn)坐標(biāo),來確定該圓的圓心和半徑。實(shí)現(xiàn)代碼如下:
import java.awt.Point; public class Circle { public Point center; public double radius; public Circle(Point p1, Point p2, Point p3) { double x1 = p1.getX(); double y1 = p1.getY(); double x2 = p2.getX(); double y2 = p2.getY(); double x3 = p3.getX(); double y3 = p3.getY(); double c = 2 * ((x1-x2)*(y1-y3) - (x1-x3)*(y1-y2)); double cx = ((y1-y3)*(x1*x1-x2*x2+y1*y1-y2*y2) + (y2-y1)*(x1*x1-x3*x3+y1*y1-y3*y3))/c; double cy = ((x1-x3)*(x1*x1-x2*x2+y1*y1-y2*y2) + (x2-x1)*(x1*x1-x3*x3+y1*y1-y3*y3))/c; center = new Point((int)cx, (int)cy); radius = Math.sqrt((cx-x1)*(cx-x1) + (cy-y1)*(cy-y1)); } }
首先,在Circle類中定義了三個Point類型的變量,用于表示給定的三個點(diǎn)的坐標(biāo)。
構(gòu)造函數(shù)中,我們可以通過以下公式來計算圓心的坐標(biāo)(cx,cy)和半徑:
c = 2 * ((x1-x2)*(y1-y3) - (x1-x3)*(y1-y2)); cx = ((y1-y3)*(x1*x1-x2*x2+y1*y1-y2*y2) + (y2-y1)*(x1*x1-x3*x3+y1*y1-y3*y3))/c; cy = ((x1-x3)*(x1*x1-x2*x2+y1*y1-y2*y2) + (x2-x1)*(x1*x1-x3*x3+y1*y1-y3*y3))/c;
然后,我們可以使用Math.sqrt()方法來計算半徑:
radius = Math.sqrt((cx-x1)*(cx-x1) + (cy-y1)*(cy-y1));
通過以上代碼,我們可以確定給定三個點(diǎn)所組成的圓的圓心和半徑。