M.Stran94 M.Stran94 - 26 days ago 20
C++ Question

C++ function output

I am trying to output the calculated area of a triangle in this program but when I try to output the area from the function I get a mixture of letters and numbers instead of the answer, if someone could point out what I am doing wrong it would be most appreciated.

I have tired tArea(area) but it gives a different error.

#include "stdafx.h"
#include <stdio.h>
#include <iostream>
#include <cmath>
using namespace std;

float tArea(float a, float b, float c, float s, float area);

int main()
{
float a, b, c;

cout << "Enter side 1: ";
cin >> a;
cout << "Enter side 2: ";
cin >> b;
cout << "Enter side 3: ";
cin >> c;

cout << "the area is" << tArea;

return 0;
}

float tArea(float a, float b, float c, float s, float area)
{
s = (a + b + c) / 2;
area = sqrt(s*(s - a)*(s - b)*(s - c));
return area;

}

Answer

You aren't calling the function. When you use the tArea name without the brackets, C++ will give you the address of the function instead of calling it, and this will be printed in hexadecimal format.

Also, you can use local variables instead of using parameters for working calculations:

#include "stdafx.h"
#include <stdio.h>
#include <iostream>
#include <cmath>
using namespace std;

float tArea(float a, float b, float c);

int main()
{
    float a, b, c;

    cout << "Enter side 1: ";
    cin >> a;
    cout << "Enter side 2: ";
    cin >> b;
    cout << "Enter side 3: ";
    cin >> c;

    cout << "the area is" << tArea(a, b, c);

    return 0;
}

float tArea(float a, float b, float c)
{
    float s = (a + b + c) / 2;
    float area = sqrt(s*(s - a)*(s - b)*(s - c));
    return area;

}
Comments