package bianjie;
|
|
import java.text.DecimalFormat;
|
|
public class ThreePointCircle {
|
|
/**
|
* 根据圆上三个点计算圆心和半径
|
*
|
* @param point1 第一个点坐标,格式 "x,y"
|
* @param point2 第二个点坐标,格式 "x,y"
|
* @param point3 第三个点坐标,格式 "x,y"
|
* @return 包含圆心和半径的字符串,例如 "圆心: 10.00,10.00; 半径: 5.00"
|
*/
|
public static String getCircleFromPoints(String point1, String point2, String point3) {
|
try {
|
// 1. 解析坐标点
|
double[] p1 = parsePoint(point1);
|
double[] p2 = parsePoint(point2);
|
double[] p3 = parsePoint(point3);
|
|
double x1 = p1[0], y1 = p1[1];
|
double x2 = p2[0], y2 = p2[1];
|
double x3 = p3[0], y3 = p3[1];
|
|
// 2. 计算分母 D
|
// 如果 D 为 0,说明三点共线,无法构成圆
|
double D = 2 * (x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2));
|
|
if (Math.abs(D) < 1e-9) {
|
return "错误: 输入的三个点共线,无法确定一个圆。";
|
}
|
|
// 3. 计算圆心坐标 (centerX, centerY)
|
// 公式:
|
// Ux = x^2 + y^2
|
// centerX = (Ux1*(y2-y3) + Ux2*(y3-y1) + Ux3*(y1-y2)) / D
|
// centerY = (Ux1*(x3-x2) + Ux2*(x1-x3) + Ux3*(x2-x1)) / D
|
|
double sumSq1 = x1 * x1 + y1 * y1;
|
double sumSq2 = x2 * x2 + y2 * y2;
|
double sumSq3 = x3 * x3 + y3 * y3;
|
|
double centerX = (sumSq1 * (y2 - y3) + sumSq2 * (y3 - y1) + sumSq3 * (y1 - y2)) / D;
|
double centerY = (sumSq1 * (x3 - x2) + sumSq2 * (x1 - x3) + sumSq3 * (x2 - x1)) / D;
|
|
// 4. 计算半径 (圆心到任意一点的距离)
|
double radius = Math.sqrt(Math.pow(centerX - x1, 2) + Math.pow(centerY - y1, 2));
|
|
// 5. 格式化输出 (保留两位小数,可根据需求调整)
|
DecimalFormat df = new DecimalFormat("#.##");
|
|
return String.format("圆心: %s,%s; 半径: %s",
|
df.format(centerX),
|
df.format(centerY),
|
df.format(radius));
|
|
} catch (NumberFormatException e) {
|
return "错误: 坐标格式不正确,请使用 'x,y' 格式 (例如: '1.5,2.5')";
|
} catch (Exception e) {
|
return "错误: " + e.getMessage();
|
}
|
}
|
|
/**
|
* 辅助方法:将字符串 "x,y" 解析为 double 数组 [x, y]
|
*/
|
private static double[] parsePoint(String pointStr) {
|
String[] parts = pointStr.split(",");
|
if (parts.length != 2) {
|
throw new IllegalArgumentException("坐标格式无效: " + pointStr);
|
}
|
double x = Double.parseDouble(parts[0].trim());
|
double y = Double.parseDouble(parts[1].trim());
|
return new double[]{x, y};
|
}
|
|
}
|