Sicily 1059. Exocenter of a Triangle

题目链接在此


求垂心。

已知三个顶点的坐标,求垂心的坐标的思路在此

当然里面没考虑各种三角形的边与x或y轴平行的情况。

参考以下源代码注释即可。


#include<iostream>
#include<stdio.h>
#include<cmath>

using namespace std;

#define INFINITE 999999.0

bool equal(double a, double b) {  //两个double类型数据不能简单地以==来判断相等
	return fabs(a - b) < 1e-6;
}

int main() {
	int testNum;
	double x1, y1, x2, y2, x3, y3; //  点A、B、C的坐标
	double x0, y0;  //  垂心坐标
	double Kah, Kch;  //  边AH和CH的斜率。点H是垂心

	cin >> testNum;
	for (int t = 1; t <= testNum; t++) {
		cin >> x1 >> y1 >> x2 >> y2 >> x3 >> y3;

		if (equal(x2, x3))  //  BC与y轴<span style="font-family: Arial, Helvetica, sans-serif;">平行</span>
			Kah = 0;
		else if (equal(y2, y3))  //  BC与x轴<span style="font-family: Arial, Helvetica, sans-serif;">平行</span>
			Kah = INFINITE;
		else
			Kah = (x2 - x3) / (y3 - y2);  //  Kah = (-1)/Kbc

		if (equal(x1, x2))  //  AB与y轴<span style="font-family: Arial, Helvetica, sans-serif;">平行</span>
			Kch = 0;
		else if (equal(y1, y2))  //  AB与x轴<span style="font-family: Arial, Helvetica, sans-serif;">平行</span>
			Kch = INFINITE;
		else
			Kch = (x1 - x2) / (y2 - y1);  //  Kch = (-1)/Kab

		//  联立并解方程:
		// (y1-y0)/(x1-x0)= Kah 
		// (y3-y0)/(x3-x0)= Kch
		if (equal(Kah, INFINITE)) {
			x0 = x1;
			y0 = y3 + (x0 - x3)* Kch;
		}
		else if (equal(Kch, INFINITE)) {
			x0 = x3;
			y0 = y1 + (x0 - x1)* Kah;
		}
		else {
			x0 = ((y1 - y3) + (Kch * x3 - Kah * x1)) / (Kch - Kah);
			y0 = y1 + (x0 - x1)* Kah;
		}

		  //  有时double型明明应该是0,但实际上是0.0……0几。
		  //  这一步真的很难想到=。=
		x0 = equal(x0, 0.0) ? 0 : x0;
		y0 = equal(y0, 0.0) ? 0 : y0;

		printf("%.4lf %.4lf\n", x0, y0);
	}

	return 0;
}

你可能感兴趣的:(sicily)