1. 程式人生 > >任意三角形外界圓的圓心和半徑

任意三角形外界圓的圓心和半徑

/**
處理:如三點共線,則返回false;否則,返回true,並將計算得到的圓心與半徑存放在center和radius眾返回。
*/
bool  triangleCircle(const Point& p1,const Point& p2,const Point& p3,Point ¢er,double &radius)  
{
	//檢查三點是否共線
	if( isThreePointsOnOneLine(p1,p2,p3) )
		return false;

	double  x1,x2,x3,y1,y2,y3;

	x1  =  p1.x; 
	x2  =  p2.x;
	x3  =  p3.x;
	y1  =  p1.y;
	y2  =  p2.y;
	y3  =  p3.y;

	//求外接圓半徑
	double a=sqrt( (x1-x2)*(x1-x2)+(y1-y2)*(y1-y2) );
	double b=sqrt( (x1-x3)*(x1-x3)+(y1-y3)*(y1-y3) );
	double c=sqrt( (x2-x3)*(x2-x3)+(y2-y3)*(y2-y3) );
	double p=(a+b+c)/2;
	double S=sqrt( p*(p-a)*(p-b)*(p-c) );
	radius=a*b*c/(4*S);

	//求外接圓圓心
	double t1=x1*x1+y1*y1;
	double t2=x2*x2+y2*y2;
	double t3=x3*x3+y3*y3;
	double temp=x1*y2+x2*y3+x3*y1-x1*y3-x2*y1-x3*y2;
	double x=(t2*y3+t1*y2+t3*y1-t2*y1-t3*y2-t1*y3)/temp/2;
	double y=(t3*x2+t2*x1+t1*x3-t1*x2-t2*x3-t3*x1)/temp/2;

	center.x  =  x  ;
	center.y  =  y  ;

	return true;
}
/**
判斷3個點是否共線
*/
bool isThreePointsOnOneLine(const Point& p1,const Point& p2,const Point& p3){
	if(p2.x==p1.x){
		if(p2.x==p3.x)
			return true;
		return false;
	}else{
		if(p2.x==p3.x)
			return true;
	}
	//判斷依據:p2與p1兩點構成直線的斜率=p2與p3兩點構成直線的斜率
	double k1=(p2.y-p1.y)/(p2.x-p1.x);
	double k2=(p3.y-p2.y)/(p3.x-p2.x);
	double DIFF=0.00000001;
	if( fabs(k1-k2)<DIFF  )
		return true;
	return false;
}