⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 vectorangle.cpp

📁 此冤码包含一组求三角形面积与夹角的实用程序。已经经过反复验证。
💻 CPP
字号:
#include <math.h>

#define MEAN_ERR 1.0E-6

template <class T> void MySwap(T &a, T &b)
{
	T p;

	p = a;
	a = b;
	b = p;
}


template <class T> double GetTriangleArea(const T P1, const T P2, const T P3)
{
	double dArea = (P2.x-P1.x)*(P3.y-P1.y) - (P3.x-P1.x)*(P2.y-P1.y);
	return (0.5*dArea);
}

template <class T> T GetTriangleArea(const T P1[2], const T P2[2], const T P3[2])
{
	T dArea = (P2[0]-P1[0])*(P3[1]-P1[1]) - (P3[0]-P1[0])*(P2[1]-P1[1]);

	return (0.5*dArea);
}

template <class T> T GetTriangleArea(const T x1, const T y1, const T x2, const T y2, const T x3, const T y3)
{
	T dArea = (x2-x1)*(y3-y1) - (x3-x1)*(y2-y1);

	return (0.5*dArea);
}


template <class T> double GetTriangleAngle(const T A, const T B, const T C)
{
//	Given the length square of three edges a, b & c, we can obtain the angle opposite against 
//	the edge a according to the cosine law: 2*sqrt(b*c) * cosA = (b+c-a).

	double a = SquareSum(B.x-C.x, B.y-C.y);
	double b = SquareSum(A.x-C.x, A.y-C.y);
	double c = SquareSum(A.x-B.x, A.y-B.y);

	if(a < MEAN_ERR || b < MEAN_ERR || c < MEAN_ERR)
	{
		::AfxMessageBox(_T("The side length of triangle is too short."));
		return 0.0;
	}

	a = (b+c-a) / (2.0*sqrt(b*c));
	if(fabs(a) >= 1.0 - MEAN_ERR)
	{
		::AfxMessageBox(_T("The angles of triangle are not correct."));

		if(a >= 1.0 - MEAN_ERR)
			a = 0.0;
		else
			a = PI;
	}
	else
		a = acos(a);
	
	return a;
}


template <class T> T GetDistanceTwoPoints(const T P1[2], const T P2[2])
{
	T x = dPt2[0] - dPt1[0];
	T y = dPt2[1] - dPt1[1];

	T dDist = x*x + y*y;
	dDist = sqrt(dDist);
	
	return dDist;
}


template <class T> T VectorAngle(const T Vector[2])
{
// ------------------------------------------------------------------
//	To calculate the direction angle between twp vectors V1 and V2, 
//	the value range is between -PI and PI.
// ------------------------------------------------------------------

	T x = Vector[0];
	T y = Vector[1];

	T dLength = sqrt(x*x + y*y);

	if(dLength < MEAN_ERR)
	{
		::AfxMessageBox(_T("The vector is too small to get the angle."));
		return 0.0;
	}

	T dAngle = 0.0;
	if(fabs(x) >= MEAN_ERR)
		dAngle = atan2(y, x);
	else if(y >= MEAN_ERR)
		dAngle = 0.5*PI;
	else if(y < -MEAN_ERR)
		dAngle = -0.5*PI;

//	if(dAngle < 0.0)
//		dAngle += TWOPI;

	return dAngle;
}	

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -