Computer Science, asked by smnsmn9914, 1 year ago

C program to calculate hypotenuse of right angled triangle

Answers

Answered by ratnajitroy02
3

// 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;  

}

Similar questions