c++ 根据给定的斜边和面积找到直角三角形的所有边(Find all sides of a right angled triangle from given hypotenuse and area)

        给定直角三角形的斜边和面积,求出其底边和高,如果给定斜边和面积的任何三角形都不可能,则打印“不可能”。

示例: 

输入:斜边 = 5,面积 = 6

输出:底边 = 3,高 = 4

输入:斜边 = 5,面积 = 7

输出:根据上述规范,不可能形成三角形。

我们可以利用直角三角形的性质来解决这个问题,具体如下:

具有固定斜边的直角三角形

在为等腰三角形时面积最大,即高

和底边相等,因此如果斜边为 H,则

根据勾股定理,
底边² + 高² = H²

要获得最大面积,底边和高应该相等,
b² + b² = H²
b = sqrt(H²/2)

以上是三角形获得最大面积时的底边长度
,给定面积必须小于此最大
面积,否则不可能出现这样的三角形。 

        现在,如果给定的面积小于此最大面积,我们可以对底边的长度进行二分查找,因为增加底边将增加面积,这是一个单调递增函数,可以轻松应用二分查找。 

        在下面的代码中,编写了一种获取直角三角形面积的方法,回想一下,对于直角三角形,面积是 ½*底边*高,可以使用勾股定理根据底边和斜边计算出高。

以下是上述方法的实现:

// C++ program to get right angle triangle, given 
// hypotenuse and area of triangle 
#include <bits/stdc++.h> 
using namespace std; 
   
//  limit for float comparison 
#define eps 1e-6 
   
// Utility method to get area of right angle triangle, 
// given base and hypotenuse 
double getArea(double base, double hypotenuse) 

    double height = sqrt(hypotenuse*hypotenuse - base*base); 
    return 0.5 * base * height; 

   
// Prints base and height of triangle using hypotenuse 
// and area information 
void printRightAngleTriangle(int hypotenuse, int area) 

    int hsquare = hypotenuse * hypotenuse; 
   
    // maximum area will be obtained when base and height 
    // are equal (= sqrt(h*h/2)) 
    double sideForMaxArea = sqrt(hsquare / 2.0); 
    double maxArea = getArea(sideForMaxArea, hypotenuse); 
   
    // if given area itself is larger than maxArea then no 
    // solution is possible 
    if (area > maxArea) 
    { 
        cout << "Not possiblen"; 
        return; 
    } 
   
    double low = 0.0; 
    double high = sideForMaxArea; 
    double base; 
   
    // binary search for base 
    while (abs(high - low) > eps) 
    { 
        base = (low + high) / 2.0; 
        if (getArea(base, hypotenuse) >= area) 
            high = base; 
        else
            low = base; 
    } 
   
    // get height by pythagorean rule 
    double height = sqrt(hsquare - base*base); 
    cout << base << " " << height << endl; 

   
// Driver code to test above methods 
int main() 

    int hypotenuse = 5; 
    int area = 6; 
   
    printRightAngleTriangle(hypotenuse, area); 
    return 0; 
}  

输出: 

3 4

时间复杂度: O(log(n)),因为使用内置 sqrt 函数

辅助空间: O(1)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

csdn_aspnet

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值