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 53 54 55 56 57 58 59 60 61 62 63 64
|
#include <iostream>
#include <algorithm> // std:max
#include <cmath> // std::sqrt
bool is_valid_triangle( double a, double b, double c )
{
// if any side has non-positive length; it is not a triangle
if( a <= 0 || b <= 0 || c <= 0 ) return false ;
// triangle inequality: longest side length is less than the semi-perimeter.
// https://en.wikipedia.org/wiki/Triangle_inequality
const double longest_side = std::max( { a, b, c } ) ;
return (a+b+c) > longest_side*2 ;
}
double get_side( const char* side_name, double min_length, double max_length )
{
std::cout << "enter the " << side_name << " side length ["
<< min_length << " to " << max_length << "]: ";
double length ;
if( std::cin >> length )
{
if( length < min_length ) std::cout << "error: length is below minimum value\n" ;
else if( length > max_length ) std::cout << "error: length is above maximumvalue\n" ;
else return length ; // valid length, return it
}
else // user did not enter a number
{
std::cout << "error: non-numeric input\n" ;
std::cin.clear() ; // clear the failed stated
std::cin.ignore( 1000, '\n' ) ; // throw the bad input line away
}
std::cout << "try again\n" ;
return get_side( side_name, min_length, max_length ) ; // try again
}
double area_of_triangle( double a, double b, double c ) // invariant: is_valid_triangle(a,b,c)
{
// heron's formula: https://en.wikipedia.org/wiki/Heron%27s_formula
const double s = (a+b+c) / 2 ; // semi-perimeter
return std::sqrt( s * (s-a) * (s-b) * (s-c) ) ;
}
int main()
{
constexpr double MIN_LENGTH = 1 ;
constexpr double MAX_LENGTH = 100 ;
static_assert( MIN_LENGTH > 0 && MIN_LENGTH < MAX_LENGTH, "bad value for min/max length" ) ;
const double a = get_side( "first", MIN_LENGTH, MAX_LENGTH ) ;
const double b = get_side( "second", MIN_LENGTH, MAX_LENGTH ) ;
const double c = get_side( "third", MIN_LENGTH, MAX_LENGTH ) ;
std::cout << "\nsides are " << a << ", " << b << " and " << c << '\n' ;
if( is_valid_triangle(a,b,c) )
{
const double area = area_of_triangle(a,b,c) ;
std::cout << "area of triangle is: " << area << '\n' ;
}
else std::cout << "these sides do not for a valid triangle\n" ;
}
|