欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

三角形垂心

程序员文章站 2024-02-21 14:32:28
...

三角形垂心

 

给定一个三角形求垂心

跟前一篇求圆心的一样。
因为发现了我之前的做法都比较二,于是乎想把整个模板都改改。
我之前的模板的做法仍就很麻烦
我先一点和该点的对边求点斜式。然后两条直线求交点。
想法简单,但是代码长度比较长,

POJ1673

point orthocenter(point p0,point p1,point p2){
 double a1,b1,a2,b2,c1,c2;
 a1 = p2.x-p1.x; b1=p2.y-p1.y;c1 = 0;
 a2 = p2.x-p0.x; b2=p2.y-p0.y;c2 = (p1.x-p0.x)*a2+(p1.y-p0.y)*b2;
 double d = a1 * b2 - a2 * b1;
  ret.x = p0.x + (c1 * b2 - c2 * b1) / d;
  ret.y = p0.y + (a1 * c2  - a2 * c1) / d;
 return ret;
}
读入三个点p0,p1,p2返回垂心
根据垂直向量点成为0
(O.x-p0.x)*(p2.x-p1.x)+(O.y-p0.y)*(p2.y-p1.y) = 0;  (1)
(O.x-p1.x)*(p2.x-p0.x)+(O.y-p1.y)*(p2.y-p0.y) = 0;  (2)
 
令O.x = x+p0.x;O.y=y+p0.y带入(1)(2)得到
x*(p2.x-p1.x)+y*(p2.y-p1.y) = 0;
x*(p2.x-p0.x)+y*(p2.y-p0.y) = (p2.x-p0.x)*(p1.x-p0.x)+(p2.y-p0.y)*(p1.y-p0.y);
解得(x,y)
O = (x,y)+p0;

 

#include<iostream>
#include<cstdio>

using namespace std;

struct point{
	double x,y;
} p0,p1,p2,ret;
int Test;

point orthocenter(point p0,point p1,point p2){
	double a1,b1,a2,b2,c1,c2;
	a1 = p2.x-p1.x; b1=p2.y-p1.y;c1 = 0;
	a2 = p2.x-p0.x; b2=p2.y-p0.y;c2 = (p1.x-p0.x)*a2+(p1.y-p0.y)*b2;
	double d = a1 * b2 - a2 * b1; 
 	ret.x = p0.x + (c1 * b2 - c2 * b1) / d; 
 	ret.y = p0.y + (a1 * c2  - a2 * c1) / d; 
	return ret;
}
int main(){
	freopen("in.txt","r",stdin);
	freopen("out.txt","w",stdout);
	cin >> Test;
	for (int ii = 1;ii<=Test;++ii){
		cin>>p0.x>>p0.y>>p1.x>>p1.y>>p2.x>>p2.y;
		ret = orthocenter(p0,p1,p2);
	     printf("%.4lf %.4lf\n",ret.x,ret.y);
	}
	return 0;
}

转载于:https://www.cnblogs.com/LitIce/archive/2011/06/06/2073627.html