Yes I thought about that but the function must be a VOID type !
Ah, gomen. A better way would throw an exception.
Code:
#include <iostream>
#include <stdexcept>
#include <cmath>
using namespace std;
// the way you had it was okay, but this is probably better
void compute_area(double&, double&, double, double, double);
int main()
{
double area,perimeter;
// always initialize if you can
int a = 8;
int b = 8;
int c = 30;
try
{
compute_area(area,perimeter,a,b,c);
cout << "The area of a triangle with sides of length " << a
<< " , " << b << " and " << c << " is " << area <<
"and the perimeter is "<<perimeter<< endl;
}
catch (const std::invalid_argument& e)
{
std::cerr << e.what() << '\n';
}
cin.get(); // better way to keep the window open
return 0;
}
void compute_area (double& area, double& perimeter, double a, double b, double c)
{
double s;
if( (a<(b+c))||(b<(a+c))||(c<(b+a)) )
{
throw std::invalid_argument("Bad combination");
}
else
{
s = (a + b + c)/ 2.0;// semiperimeter
area = sqrt (s*(s-a)*(s-b)*(s-c)); // area triangle
perimeter=a+b+c;
}
}
That's probably not allowed. The only other way I can think of is a global variable to flag errors. It's a bad option though. I only mention it because it seems like your teacher is forcing that kind of error handling method.
Code:
#include <iostream>
#include <stdexcept>
#include <cmath>
using namespace std;
namespace
{
bool error = false;
}
// the way you had it was okay, but this is probably better
void compute_area(double&, double&, double, double, double);
int main()
{
double area,perimeter;
// always initialize if you can
int a = 8;
int b = 8;
int c = 30;
compute_area(area,perimeter,a,b,c);
if (!error)
{
cout << "The area of a triangle with sides of length " << a
<< " , " << b << " and " << c << " is " << area <<
"and the perimeter is "<<perimeter<< endl;
}
cin.get(); // better way to keep the window open
return 0;
}
void compute_area (double& area, double& perimeter, double a, double b, double c)
{
double s;
if( (a<(b+c))||(b<(a+c))||(c<(b+a)) )
{
std::cerr << "Bad combination\n";
error = true;
}
else
{
s = (a + b + c)/ 2.0;// semiperimeter
area = sqrt (s*(s-a)*(s-b)*(s-c)); // area triangle
perimeter=a+b+c;
}
}