这C++创建三角形的代码是什么意思

what does this C++ code to create a triangle mean?

本文关键字:代码 是什么 意思 三角形 C++ 创建      更新时间:2023-10-16

这个 c++ 代码是什么意思?

我试图弄清楚这段代码的含义,但作为编程 IV 的新手,运气不佳。这是创建等边三角形的代码。

static const float COS_60 = 0.5f;
static const float COS_30 = 0.5f * sqrt(3.f);
const float side = radius * 2.f * COS_30;
const float bottomHeight = point.getY() - COS_60 * radius;

this->vertices.push_back(Vertex(point.getX(), point.getY() + radius));
this->vertices.push_back(Vertex(point.getX() + COS_60 * side, bottomHeight));
this->vertices.push_back(Vertex(point.getX() - COS_60 * side, bottomHeight));

等边三角形具有三个等长的边。拐角的角度(在内侧)是 60 度,因此需要COS_60。碰巧的是 COS 60 = 0.5,所以程序员没有编写代码来计算它,而只是使用了这个"已知值"。

边的长度为 radius * 2.f * COS_30(即从中心到最远角乘以 30 度的余弦距离)。COS_30恰好是sqrt(3)/20.5f * sqrt(3.f).同样,你可以计算这个,例如使用计算器,而不是把它写成 0.5 * sqrt(3)。或者,如果你想使用C++函数,你可以使用sin(30.0f * 2.f * pi / 180.0f)[这是因为计算机上的数学几乎总是以弧度而不是度为单位完成]。

从底部到中心的距离为 COS_60 * radius(半径的一半)。

如果我们手动应用这个数学,给定 X、Y 中心为 400、400 和半径为 100,我们得到:

side = 100 * 2 * COS_30 => 200*0.866 = 173;
bottomheight = 400 - COS_60 * radius = 400 - 50 = 350

然后是以下坐标:

400, (400 + radius)    => 400, 500
400 + COS_60 * side, 350    => 400 + 173 * 0.5, 350 => 486, 350 
400 - COS_60 * side, 350    => 400 - 173 * 0.5, 350 => 314, 350