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

I’m trying to calculate the area, but keep getting 0.
What am I doing wrong?

  1 #include <iostream>
  2 using namespace std;
  3 
  4 int main() {
  5   int area, base, height;
  6 
  7   area = (1/2)*base*height;
  8 
  9   cout << "Enter the base: ";
 10   cin >> base;
 11 
 12   cout << "Enter the height: ";
 13   cin >> height;
 14 
 15   cout << "The area is: " << area << endl;
 16 
 17 
 18 }

>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.

Leave a Reply