Search code examples
c++area

I'm trying to calculate the area of the triangle, but keep getting area = 0


I'm trying to calculate the area of a triangle, but keep getting 0.

What am I doing wrong?

#include <iostream>
using namespace std;

int main() {
  int area, base, height;

  area = (1/2)*base*height;

  cout << "Enter the base: ";
  cin >> base;

  cout << "Enter the height: ";
  cin >> height;

  cout << "The area is: " << area << endl;
}

Solution

  • You're trying to calculate the area before you know the base and height. So the answer is going to be undefined, because base and height haven't been set (depending on how your compiler does things, it may set unknown variables to 0, or it may let them be random values. Either way it won't work). Wait until after the user enters the number to do the calculation.