在C++编程中,在二维平面内的多个点,找出三个点,可以满足指定的边长构成一个三角形,如何编程?
时间: 2025-07-06 18:57:33 浏览: 6
### C++算法实现
为了在二维平面上找到能够构成特定边长三角形的三个点,可以采用基于余弦定理的方法。给定三边长度 \(a\)、\(b\) 和 \(c\),其中任意两边之和大于第三边以满足三角不等式条件。
假设第一个顶点位于原点 \((0, 0)\),第二个顶点沿X轴放置于\((c, 0)\)位置,则第三个顶点坐标可通过下面公式计算得出:
\[ x_3 = b \cos(\theta) \]
\[ y_3 = b \sin(\theta) \]
这里角度 \(\theta\) 可通过如下方式求得:
\[ \cos(\theta)=\frac{a^{2}+c^{2}-b^{2}}{2ac}\]
下面是完整的C++代码示例用于解决问题:
```cpp
#include <iostream>
#include <cmath>
struct Point {
double x;
double y;
Point(double _x=0.0, double _y=0.0): x(_x), y(_y){}
};
Point calculateThirdVertex(double a, double b, double c){
// Calculate angle theta using cosine rule.
double cosTheta=(pow(a,2)+pow(c,2)-1, 1] range due to floating point errors.
if(cosTheta<-1) cosTheta=-1;
else if(cosTheta>1) cosTheta=1;
double sinTheta=sqrt(1-pow(cosTheta,2));
return Point(a*cosTheta,a*sinTheta);
}
int main(){
double sideA,sideB,sideC;
std::cout<<"Enter sides of triangle: ";
std::cin>>sideA>>sideB>>sideC;
// Check whether input forms valid triangle according to Triangle Inequality Theorem.
if(sideA + sideB <= sideC || sideA + sideC <= sideB || sideB + sideC <= sideA){
std::cerr << "Invalid dimensions for forming a triangle."<<std::endl;
return -1;
}
Point p1,p2(sideC,0),p3;
p3=calculateThirdVertex(sideA,sideB,sideC);
std::cout<<"\nCoordinates are:\nP1:"<<p1.x<<","<<p1.y
<<"\nP2:"<<p2.x<<","<<p2.y
<<"\nP3:"<<p3.x<<","<<p3.y<<'\n';
return 0;
}
```
此程序首先验证输入的数据能否组成合法的三角形;接着定义两个固定端点的位置,并调用 `calculateThirdVertex` 函数获取最后一个未知顶点的具体坐标[^1]。
阅读全文
相关推荐


















