在 C++ 中查找直角三角形的尺寸
在这个问题中,我们给定两个值 H 和 A,分别表示直角三角形的斜边和面积。我们的任务是查找直角三角形的尺寸。
直角三角形是一种特殊的三角形,其中两条边相交成直角。

图:直角三角形
让我们举个例子来理解这个问题,
Input : H = 7 , A = 8 Output : height = 2.43, base = 6.56
解决方案方法
这个问题的解决方案可以通过使用值的数学公式找到。让我们在这里推导出它们,
$A\:=\:1/2^*h^*b$
$H^2\:=\:h^2\:+\:b^2$
使用公式,
$(h+b)^2\:=\:h^2+b^2+2^*h^*b$
$(h+b)^2\:=\:H^2+4^*A$
$(h+b)\:=\:\sqrt(H^2+4^*A)$
类似地,使用公式,
$(h-b)^2\:=\:h^2+b^2-2^*h^*b$
$(h-b)^2\:=\:H^2-4^*A$
$(h-b)^2\:=\:\sqrt(H^2-4^*A)$
这里,我们有两个方程,
将两者相加,我们得到
$h-b+h-b\:=\:\sqrt(H^2-4^*A)\:+\:\sqrt(H2-4^*A)$
$2h\:=\:(\sqrt(H^2-4^*A))\:+\:(\sqrt(H^2-4^*A))$
$h\:=\:1/2^*(\sqrt(H^2-4^*A))\:+\:(\sqrt(H^2-4^*A))$
将两者相减,我们得到,
$h-b-h+b\:=\:\sqrt(H^2-4^*A)-\sqrt(H^2-4^*A)$
$2b\:=\:(\sqrt(H^2-4^*A)\:-\:\sqrt(H^2-4^*A))$
$b\:=\:1/2^*(\sqrt(H^2-4^*A)\:-\:\sqrt(H^2-4^*A))$
应用这两个公式来获得 b 和 h 的值。
示例
程序说明我们解决方案的工作原理
#include <iostream>
#include <math.h>
using namespace std;
void findAllDismensionsRightTriangle(int H, int A) {
if (H * H < 4 * A) {
cout<<"Not Possible\n";
return;
}
float val1 = (float)sqrt(H * H + 4 * A);
float val2 = (float)sqrt(H * H - 4 * A);
float b = (float)(val1 + val2) / 2.0;
float p = (float)(val1 - val2) / 2.0;
cout<<"Perpendicular = "<<p<<endl;
cout<<"Base = "<<b;
}
int main() {
int H = 7;
int A = 8;
cout<<"The dimensions of the triangle are : \n";
cout<<"Hypotenuse = "<<H<<endl;
findAllDismensionsRightTriangle(H, A);
return 0;
}输出
The dimensions of the triangle are : Hypotenuse = 7 Perpendicular = 2.43845 Base = 6.56155
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP