I'm quite new to C++, just taking my first course now in University. I have this assignment where I have to write a program where the user inputs the X,Y points of a triangle, and then outputs the area. Things are mostly fine, but instead of an actual output, I just get nan instead. What am I doing wrong? Is it something with the math, or the code?
#include <iostream>
#include <cmath>
usingnamespace std;
int main()
{
int x1,x2,x3,y1,y2,y3;
double side1 = sqrt ( (x1-x2)*(x1-x2) + (y1-y2)*(y1-y2) );
double side2 = sqrt ( (x2-x3)*(x2-x3) + (y2-y3)*(y2-y3) );
double side3 = sqrt ( (x3-x1)*(x3-x1) + (y3-y1)*(y3-y1) );
double s = (side1 + side2 + side3)/2;
double area = sqrt( s * (s - side1) * (s - side2) * (s - side3));
cout << "This program will help you find the area of a triangle" << endl;
cout << "Please enter X of point A : ";
cin >> x1;
cout << "Please enter Y of point A : ";
cin >> y1;
cout << "Please enter X of point B : ";
cin >> x2;
cout << "Please enter Y of point B : ";
cin >> y2;
cout << "Please enter X of point C : ";
cin >> x3;
cout << "Please enter Y of point C : ";
cin >> y3;
cout << "The area is... " << area << "!" << endl;
return 0;
}
I haven't taken a thorough look at the maths but try these;
1. initialize your x's and y's
2. Your calculations should either be in a function or
you must initialize x and y (before your calculations) or
take your calculations after you have all your inputs. Otherwise, line 12 gives garbage.
If your arithmetic is correct, then try steps 1 & 2 before looking further.
You are trying to calculate the area (Heron's formula) ... before you have actually entered any points!
Apart from that, it would be more useful if x1, x2 etc were doubles, rather than ints. To speed up input, consider also inputting both x and y coordinates in the same statement.
#include <iostream>
#include <cmath>
usingnamespace std;
int main()
{
double x1,x2,x3,y1,y2,y3;
cout << "This program will help you find the area of a triangle" << endl;
cout << "Please enter X of point A : ";
cin >> x1;
cout << "Please enter Y of point A : ";
cin >> y1;
cout << "Please enter X of point B : ";
cin >> x2;
cout << "Please enter Y of point B : ";
cin >> y2;
cout << "Please enter X of point C : ";
cin >> x3;
cout << "Please enter Y of point C : ";
cin >> y3;
double side1 = sqrt ( (x1-x2)*(x1-x2) + (y1-y2)*(y1-y2) );
double side2 = sqrt ( (x2-x3)*(x2-x3) + (y2-y3)*(y2-y3) );
double side3 = sqrt ( (x3-x1)*(x3-x1) + (y3-y1)*(y3-y1) );
double s = (side1 + side2 + side3)/2;
double area = sqrt (s * (s - side1) * (s - side2) * (s - side3));
cout << "The area is... " << area << "!" << endl;
return 0;
}