C++ code for area of triangle, compiling but not working
May 23, 2016 at 6:29am UTC
This program is to find the area of a triangle using three vertices. I have used Heron's formula to do this. The program compiles but I get these warnings in the main function:
37:21: warning: variable 'aTriangle' set but not used [-Wunused-but-set-variable]
45:7: warning: 'area' is used uninitialized in this function [-Wuninitialized]
I get the first one at the struct triangle aTriangle declaration and the second at cout area. The output of the program is 0. I don't understand why.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
//-----Include required headers here-----
#include<iostream>
#include<cmath>
using namespace std;
//-----End of headers-----
//-----Don't change/delete structs-----
struct vertex{
float x;
float y;
};
struct triangle{
vertex vertices[3];
};
//-----Structs end here
//-----Add new functions here(if any)-----
//-----New functions end here-----
float cal_area(triangle aTriangle) {
//Write your solution below this line
float s,area,a,b,c;
a=sqrt(pow((aTriangle.vertices[1].x-aTriangle.vertices[2].x),2)-pow((aTriangle.vertices[1].y-aTriangle.vertices[2].y),2));
b=sqrt(pow((aTriangle.vertices[2].x-aTriangle.vertices[3].x),2)-pow((aTriangle.vertices[2].y-aTriangle.vertices[3].y),2));
c=sqrt(pow((aTriangle.vertices[1].x-aTriangle.vertices[3].x),2)-pow((aTriangle.vertices[1].y-aTriangle.vertices[3].y),2));
s=0.5*(a+b+c);
area=sqrt(s*(s-a)*(s-b)*(s-c));
return (area);
//Dont write below this line
}
int main()
{ float area;
struct triangle aTriangle;
aTriangle.vertices[1].x=1;
aTriangle.vertices[2].x=2;
aTriangle.vertices[3].x=5;
aTriangle.vertices[1].y=4;
aTriangle.vertices[2].y=5;
aTriangle.vertices[3].y=20;
float cal_area(triangle aTriangle);
cout<<area<<endl;
return 0;
}
May 23, 2016 at 7:00am UTC
line 49, you're not actually calling the function.
Try change it to:
area = calc_area(aTriangle);
Topic archived. No new replies allowed.