Search code examples
c++areadev-c++

In C++ .is triangle area showing zero??? why?


The area of triangle is showing zero in the output, why is that??
What have i done wrong??

#include <iostream>
using namespace std;

int main() {
  int Base, Height, Area;

  // >>> Is anything wrong with the formula??
  Area = (0.5) * Height * Base;

  cout << "To find the Area of Triangle" << endl << endl;

  // Base
  cout << "Enter Base length:";
  cin >> Base;
  cout << endl;

  // Height
  cout << "Enter Height length";
  cin >> Height;
  cout << endl << endl;

  cout << "Your Base Length is:" << Base << endl;
  cout << "Your Height Length is:" << Height << endl;

  // calculating area of triangle

  // >>> This is the part output is zero
  cout << "Area of the triangle is :" << Area << endl;
}

Solution

  • When you have a computed value you must compute it with any changes made to the values involved. Unlike algebra where x = y * 2 means "x is by definition y times two", in C++ it means "assign to x the value of y times 2 as it is right now" and has no bearing on the future.

    For something calculated you use a function:

    int Area(const int Height, const int Base) {
      return 0.5 * Height * Base;
    }
    

    Where now you can call it:

    cout<<"Area of the triangle according to your measurements is :"<<Area(Height, Base)<<endl<<endl;