2

I am trying to create a program in C++ to calculate the area of a triangle using functions. I keep getting back 0 as my answer for the area, not sure what I'm doing wrong. I've included my code below. I'm new to using functions any help or suggestions would be greatly appreciated.

#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;

// complete the following three functions

// The function InputBaseHeight will read the values for the Base and Height of a Triangle from the keyboard
// and pass the Base and Height values back through a reference parameter.

void InputBaseHeight(double height, double Base)
{
cout << "\n Enter height = "; cin >> height;
cout << "\n Enter Base = "; cin >> Base;
}

// The function TriangleArea will receive the Base and Height values through a value parameter and
// return the Area of the Triangle through the function name

double TriangleArea(double height, double Base, double Area)
{
// Area = 1/2 * Base * Height
return Area = Base/2 * height;


}
// The function PrintArea will receive the Area value through a value parameter
// and label and print the Area value.


void PrintArea(double height, double Base, double Area)
{


cout << "\n The area of the triangle = " << Area;
}


int main()
{
   double Base = 0.0, height = 0.0, Area = 0.0;

// call InputBaseHeight function

InputBaseHeight(height, Base);

// call TriangleArea function

TriangleArea(height, Base, Area);

// call PrintArea

PrintArea(height, Base, Area);

cout<< "\n\n The End";
return 0;

}
Aaron
  • 77
  • 1
  • 2
  • 6
  • 1
    @Jason The OP does not know about it for sure, he is lost and does not know where the problem resides. – ProXicT Oct 10 '16 at 23:05
  • @ProXicT I am positive that if the OP reads the linked question, much will become clear. See also related: http://stackoverflow.com/questions/11736306/when-pass-a-variable-to-a-function-why-the-function-only-gets-a-duplicate-of-th and http://stackoverflow.com/questions/10972662/c-change-functions-variable-argument and also http://www-h.eng.cam.ac.uk/help/tpl/languages/C++/argsC++.html and possibly a few nuts-and-bolts tutorials here and there. – Jason C Oct 10 '16 at 23:06
  • 1
    Because you didnt actually change the variable. Your suppose to use a refrence in C++: `double TriangleArea(double height, double Base, double &Area) { // Area = 1/2 * Base * Height return Area = Base/2 * height; }` Or you can change your main.cpp up a bit: `Area = TriangleArea(height, Base, Area);` And finally you need refrences here. `void InputBaseHeight(double &height, double &Base)` .. Was about to say that in an answer but question got closed :/ – amanuel2 Oct 10 '16 at 23:07
  • @amanuel2 Thanks, I guess i'm not sure when and where to use the &. This is all new to me, so I appreciate the help. – Aaron Oct 10 '16 at 23:33
  • @Aaron Its called [referencing](http://www.cprogramming.com/tutorial/references.html) .. – amanuel2 Oct 10 '16 at 23:38

0 Answers0