Advertisement
Guest User

Untitled

a guest
Oct 8th, 2021
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.42 KB | None | 0 0
  1. #include <iostream>
  2. #include <cmath>
  3.  
  4. using namespace std;
  5.  
  6. const float eps = 1e-20f; //10^-20
  7.  
  8. int Validate(float a, float b, float c, float d)
  9. {
  10.     float side[4] = {a, b, c, d};
  11.     float sum     = 0.0f;
  12.    
  13.     //if at least one side < 0.0 -> not trapezoid!
  14.     for(int i = 4; i--; sum += side[i])
  15.         if(side[i] <= 0.0f)
  16.             return 0;
  17.    
  18.     //if at least one side >= sum of other three sides -> not trapezoid!
  19.     for(int i = 4; i--; )
  20.         if(side[i] >= sum - side[i])
  21.             return 0;
  22.    
  23.     //parallellogram isn't trapezoid! area can not be found!
  24.     if(fabs(a - b) < eps)
  25.         return 0;
  26.    
  27.     //additional check to distinguish quadrangle from trapezoid
  28.     float ab  =  a - b;
  29.     float arg = (d * d - c * c - ab * ab) / (2.0f * c * ab);
  30.    
  31.     return fabs(arg) < 1.0f;
  32. }
  33.  
  34. float Area(float a, float b, float c, float d)
  35. {
  36.     if(!Validate(a, b, c, d))
  37.         return -1.0f;
  38.    
  39.     //trapezoid area through four sides
  40.    
  41.     float ab = a - b;
  42.     float t  = 0.5f * (ab * ab + c * c - d * d) / ab;
  43.    
  44.     return (a + b) * 0.5f * sqrtf(c * c - t * t);
  45. }
  46.  
  47. int main()
  48. {
  49.     float a, b, c, d;
  50.    
  51.     cout << "Base 1 = ";
  52.     cin  >> a;
  53.    
  54.     cout << "Base 2 = ";
  55.     cin  >> b;
  56.    
  57.     cout << "Side 1 = ";
  58.     cin  >> c;
  59.    
  60.     cout << "Side 2 = ";
  61.     cin  >> d;
  62.    
  63.     float s = Area(a, b, c, d);
  64.    
  65.     if(s < 0.0f)
  66.         cout << "Not trapezoid!" << endl;
  67.     else
  68.         cout << "Area = " << s << endl;
  69.    
  70.     return 0;
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement