Problem with Heron's formula

Hi, I've only started this week programing on C++ so my resources are still quite limited, but here's the thing, the code is supposed to calculate the area of any given triangle by using Heron's formula, but sometimes the answer shows the actual result, sometimes it shows "0", and somtimes "Nan", depending on the values you assign.
I.e: 2.2, 3.2, 5.1, shows "2.21897 (actual result).
90, 80, 10: Shows "Area: 0"
and 5, 60, 3: Shows "Area: nan"

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
  #include <iostream>
#include <string>
#include <sstream>
#include <cmath>
using namespace std;

int main ()
{
	string mystring;
	double side1, side2, side3, result, p, q;
	cout << "Input length of the sides \n";
	getline (cin, mystring);
	stringstream (mystring) >> side1;
	getline (cin, mystring);
	stringstream (mystring) >> side2;
	getline (cin, mystring);
	stringstream (mystring) >> side3;
	q = (side1+side2+side3);
	p = (q)/2;
	result = sqrt(p*(p-side1)*(p-side2)*(p-side3));
	cout << "Area:  \n";
	cout << result << endl;
	cout << "Perimeter: \n" << q << endl;
	return 0;	
}
Well 5 60 3 couldn't possibly be a triangle because the two short sides wouldn't reach from one end of the long side to the other. And 90 80 10 would be a straight line.
Like what shadomouse said. Your code works well. But... it makes me wonder. Why make it so complicated as to use strings and everything?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <cmath>
using namespace std;

int main ()
{
	double side1, side2, side3, result, p;
	cout << "Input length of the sides \n";
	cin >> side1 >> side2 >> side3;
	
	p = (side1+side2+side3)/2;
	
	result = sqrt(p*(p-side1)*(p-side2)*(p-side3));
	
	cout << "Area:  \n" << result << endl;
	cout << "Perimeter: \n" << side1+side2+side3 << endl;

	return 0;	
}
Ahh, I see, So it's just that I was trying random numbers that didn't work in a triangle, awesome then. And I've only started with c++ this week as a hobby, with a pdf tutorial, so I'm trying stuff to see how they work, that's why it's unnecessarily complicated.
Thank you, people.
Last edited on
Topic archived. No new replies allowed.