牛客C++面经——给定三角形ABC和一点P(x,y,z),判断点P是否在ABC内

目录

 

思路:

计算面积的方法:海伦公式

注意:

代码:

参考:


思路:

根据面积法,如果P在三角形ABC内,那么三角形ABP的面积+三角形BCP的面积+三角形ACP的面积应该等于三角形ABC的面积。

计算面积的方法:海伦公式

S为半周长,A为面积。

原题解的计算方法比这个简洁一些但是我没有看懂。。。

注意:

  • 判断浮点数是否相等的方法
  • 代码书写习惯
     

代码:

//C++面经(1 )
/*给定三角形ABC和一点P(x,y,z),判断点P是否在ABC内,给出思路并手写代码 */ 
//思路:面积法 
#include <iostream>
#include <cmath> 
using namespace std;

static const float ABS_FLOAT_0=0.0001;

//存储坐标 
struct point_float{
	float x;
	float y;
}; 

//计算三角形的面积
//使用海伦公式求解 
float GetTriangleSquar(const point_float pt0, const point_float pt1, const point_float pt2){
	point_float AB,BC,CA;
	float ab,bc,ca;
	AB.x = pt1.x - pt0.x;
	AB.y = pt1.y - pt0.y;
	ab=sqrt((AB.x)*(AB.x)+(AB.y)*(AB.y));
	BC.x = pt2.x - pt1.x;
	BC.y = pt2.y - pt1.y;
	bc=sqrt((BC.x)*(BC.x)+(BC.y)*(BC.y)); 
	CA.x = pt2.x - pt0.x;
	CA.y = pt2.y - pt0.y;
	ca=sqrt((CA.x)*(CA.x)+(CA.y)*(CA.y));
	float C=(ab+bc+ca)/2.0f;//半周长 
	return sqrt(C*(C-ab)*(C-bc)*(C-ca));
}

//判断给定一点是否在三角形内或边上
bool IsInTriangle(const point_float A, const point_float B, const point_float C, const point_float D)
{
	float SABC, SADB, SBDC, SADC;
	SABC = GetTriangleSquar(A, B, C);
	SADB = GetTriangleSquar(A, D, B);
	SBDC = GetTriangleSquar(B, D, C);
	SADC = GetTriangleSquar(A, D, C);
	float SumSuqar = SADB + SBDC + SADC;
	//注意判断浮点数的方法! 
	if ((-ABS_FLOAT_0 < (SABC - SumSuqar)) && ((SABC - SumSuqar) < ABS_FLOAT_0)){
		return true;
	}else{
		return false;
	}
}

int main(){
	
	point_float pt0,pt1,pt2;
	point_float P; 
	pt0.x=0.0f;
	pt0.y=0.0f;
	pt1.x=3.0f;
	pt1.y=0.0f;
	pt2.x=0.0f;
	pt2.y=4.0f;
	P.x=1.5f;
	P.y=2.0f;
//	cout<<GetTriangleSquar(pt0,pt1,pt2)<<endl;
	cout<<IsInTriangle(pt0,pt1,pt2,P)<<endl;
	
	return 0;
} 

参考:

https://www.nowcoder.com/tutorial/93/a34ed23d58b84da3a707c70371f59c21

发布了228 篇原创文章 · 获赞 76 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/qq_41895747/article/details/103946654
今日推荐