在 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