In C++ using Heron\'s formula for the area A of a triangle with sides of length
ID: 3857889 • Letter: I
Question
In C++ using
Heron's formula for the area A of a triangle with sides of length a, b and c is:
where s = (a + b + c)/2
Write, test (=3 points) and execute a function that accepts the values a, b, and c as parameters, and then calculates the values of s (=1 point) and (s(s-a)(s-b)(s-c) (=1 point). If this quantity is positive, the function calculates A (=1 point). If the quantity is negative, a, b and c do not form a triangle, and the function should set A= - 1 (=1 point). The value of A should be returned by the function (=1 point)
Explanation / Answer
Step 1: Lets Derive Test Cases First
The program should statisfy all this Tests.
Step 2......................xxxxxxxxxxxxxxxLETS SEE PROGRAMxxxxxxxxxxxxxxxxxxxxxx................................................
#include <iostream>
#include<math.h>
using namespace std;
// Function for Calculating Area
float area(float a,float b,float c)
{
float ar,s,temp; //ar,s stands for Area and s half perimeter
s = (a+b+c)*0.5; // Calculating s
temp = s*(s-a)*(s-b)*(s-c);
if(temp>0) // if temp positive calculate area
{
ar = sqrt(temp);
}
else
{
ar = -1; // Setting Value of A as -1 when temp is negative
}
return ar; // Returning value of A
}
int main()
{
float b,a,c;
float result;
std::cout << "Enter Value of a,b,c";
std::cin >> a >> b >> c;
result = area(a,b,c); // Passing sides to function area
cout << result;
}