-4
#include <iostream>
#include <math.h>

using namespace std;

int main()
{
    int l,b,h;
    int s;
    s=(l+b+h);
    float ar=s*(s-l)*(s-b)*(s-h);
    float area;
    int ch;
    cout<<"How do you want to calculate the area?"<<endl;
    cout<<"1) simple formula"<<endl<<"2) heron's formula"<<endl;
    cin>>ch;
    if(ch==1){
        cout<<"Enter the sides of the triangle."<<endl;
        cin>>l>>b>>h;
        area=0.5*(b*h);
        cout<<"Area of the triangle is = "<<area<<endl;
    }
    else if (ch==2){
        cout<<"Enter the sides of the triangle."<<endl;
        cin>>l>>b>>h;
        cout<<s<<endl<<l+b+h<<endl;
        cout<<"The calculated area of the triangle is = "<<sqrt(ar)<<endl;
    }
    return 0;
}

It prints the correct value for l+b+h but, for s, it displays a huge negative number .I've tried changing the data type of s too. This happens in almost all my programs.

MD. Khairul Basar
  • 4,976
  • 14
  • 41
  • 59

1 Answers1

0

s is computed once (by reading uninitialized values, so UB).

You may create lambda instead:

auto s = [&](){ return l + b + h; };
auto ar = [&](){ return s() * (s() - l) * (s() - b) * (s() - h); };

and then

cout << "Enter the sides of the triangle." << endl;
cin >> l >> b >> h;
cout << s << endl << l + b + h << endl;
cout << "The calculated area of the triangle is = " << sqrt(ar) << endl;

Or simply compute the value after setting the values

cout << "Enter the sides of the triangle." << endl;
cin >> l >> b >> h;
const int s = l + b + h;
const int ar = s * (s - l) * (s - b) * (s - h);

cout << s << endl << l + b + h << endl;
cout << "The calculated area of the triangle is = " << sqrt(ar) << endl;
Jarod42
  • 203,559
  • 14
  • 181
  • 302