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 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
|
#include <iostream>
#include <cmath>
using namespace std;
void description();
void get_input(double& side_a, double& side_b, double& side_c);
bool isTriangle(double side_a, double side_b, double side_c);
double semiperimter(double side_a, double side_b, double side_c);
void area_perimeter(double side_a, double side_b, double side_c, double& perimeter, double& area);
void show_output(double perimeter, double area);
int main ()
{
char answer(0);
double perimeter, area, side_a, side_b, side_c;
do
{
description();
get_input(side_a, side_b, side_c);
if (isTriangle(side_a, side_b, side_c))
{
area_perimeter(side_a, side_b, side_c, perimeter, area);
}
while (!isTriangle(side_a, side_b, side_c))
{
cout << "\nThe side lengths you entered cannot form a triangle.\n";
cout << "Change one or more side lengths and try again.\n";
get_input(side_a, side_b, side_c);
}
show_output(perimeter, area);
cout << "Would you like to run this program again? (Y or y)\n";
cin >> answer;
}
while (answer == 'y' || answer == 'Y');
return 0;
}
void description()
{
cout << "\nThis program calculates the perimeter and area of a triangle\n";
cout << "based on user input of three side lengths.\n\n";
}
void get_input(double& side_a, double& side_b, double& side_c)
{
cout << "Input the lengths of three sides of a triangle:\n";
cin >> side_a;
while (side_a <= 0)
{
cout << "Enter a positive nonzero number";
cin >> side_a;
}
cin >> side_b;
while (side_b <= 0)
{
cout << "Enter a positive nonzero number";
cin >> side_b;
}
cin >> side_c;
while (side_c <= 0)
{
cout << "Enter a positive nonzero number";
cin >> side_c;
}
cout << "The side lengths of the three sides are: " << side_a << ", " << side_b << ", " << side_c << ".\n\n"; //Echo user input
}
bool isTriangle(double side_a, double side_b, double side_c)
{
if (side_a + side_b > side_c && side_a + side_c > side_b && side_b + side_c > side_a)
return true;
else
return false;
}
double semiperimter(double side_a, double side_b, double side_c)
{
double semiPer;
semiPer = (side_a + side_b + side_c)/2;
return semiPer;
}
void area_perimeter(double side_a, double side_b, double side_c, double& perimeter, double& area)
{
double semiPer;
semiPer = semiperimter(side_a, side_b, side_c);
perimeter = side_a + side_b + side_c;
area = sqrt (semiPer*(semiPer - side_a)*(semiPer - side_b)*(semiPer - side_c));
}
void show_output(double perimeter, double area)
{
cout << "The perimeter of the triangle is " << perimeter << " units.\n"; //I wasn't sure if I should ask the user
cout << "The area of the triangle is " << area << " square units.\n"; //to input their units in also so I just
} //wrote units
|