計算幾何的題目,三點確定一個圓。
#include <stdio.h>
#include <math.h>
struct Line {
int no_slope;
double k;
double i_x;
double i_y;
};
struct Point {
double x;
double y;
};
const double E = 1e-5;
bool double_cmp(double a, double b) {
return fabs(a-b) < E;
}
Line set_line(const Point& p1, const Point& p2) {
Line tmp;
if (double_cmp(p1.x, p2.x)) {
tmp.no_slope = true;
tmp.i_x = p1.x;
}
else {
tmp.no_slope = false;
tmp.k = (p2.y-p1.y)/(p2.x-p1.x);
tmp.i_y = p1.y-tmp.k*p1.x;
}
return tmp;
}
Line get_vertical(const Line& l, const Point& p) {
Line tmp;
if (l.no_slope == true) {
tmp.no_slope = false;
tmp.k = 0.0;
tmp.i_y = p.y;
}
else if (double_cmp(l.k, 0.0)) {
tmp.no_slope = true;
tmp.i_x = p.x;
}
else {
tmp.no_slope = false;
tmp.k = -1/l.k;
tmp.i_y = p.y - tmp.k*p.x;
}
return tmp;
}
int main() {
double x,y,r;
double ax,ay,bx,by,cx,cy;
Point a,b,c;
Point mid1,mid2;
Line l1,l2,v1,v2;
int flag=0;
while (scanf("%lf",&ax)!=EOF) {
scanf("%lf%lf%lf%lf%lf", &ay,&bx,&by,&cx,&cy);
a.x=ax;
a.y=ay;
b.x=bx;
b.y=by;
c.x=cx;
c.y=cy;
mid1.x=(a.x+b.x)/2;
mid1.y=(a.y+b.y)/2;
mid2.x=(a.x+c.x)/2;
mid2.y=(a.y+c.y)/2;
l1=set_line(a,b);
l2=set_line(a,c);
v1=get_vertical(l1,mid1);
v2=get_vertical(l2,mid2);
if (v1.no_slope) {
x = v1.i_x;
y = v2.k*x + v2.i_y;
}
else if (v2.no_slope) {
x = v2.i_x;
y = v1.k*x + v1.i_y;
}
else {
x = (v1.i_y - v2.i_y) / (v2.k - v1.k);
y = v1.k*x + v1.i_y;
}
r = sqrt((ax-x)*(ax-x)+(ay-y)*(ay-y));
char c1, c2,c3;
if (x>0)
c1='-';
else
c1='+';
if (y>0)
c2='-';
else
c2='+';
printf("(x %c %.3lf)^2 + (y %c %.3lf)^2 = %.3lf^2\n",c1,fabs(x),c2,fabs(y),r);
double t1=-2.0*x;
double t2=-2.0*y;
double t3=x*x+y*y-r*r;
if (t1>=0)
c1='+';
else
c1='-';
if (t2>=0)
c2='+';
else
c2='-';
if (t3>=0)
c3='+';
else
c3='-';
printf("x^2 + y^2 %c %.3lfx %c %.3lfy %c %.3lf = 0\n",c1,fabs(t1),c2,fabs(t2),c3,fabs(t3));
printf("\n");
// printf("%.3lf %.3lf %.3lf\n", x, y, r);
}
return 0;
}