-
stcuk in loop
why is my program stuck in the last while loop? compile this code.. then enter 3,4,5 for a,b,c and then enter "y'' for your choice to continue... it continues to loop forever
Code:
#include <iostream.h>
#include <math.h>
#include <string.h>
int main ()
{
double a, b, c, s, area, perimeter, choice;
do
{
do
{
cout << "Enter side a of the triangle: ";
cin >> a;
while (a <= 0)
{
cout << "The sides of a triangle must be greater than 0." <<endl;
cout << "Please enter a number greater than 0: ";
cin >> a;
}
cout << "Enter side b of the triangle: ";
cin >> b;
while (b <= 0)
{
cout << "The sides of a triangle must be greater than 0." <<endl;
cout << "Please enter a number greater than 0: ";
cin >> b;
}
cout << "Enter side c of the triangle: ";
cin >> c;
while (c <= 0)
{
cout << "The sides of a triangle must be greater than 0." <<endl;
cout << "Please enter a number greater than 0: ";
cin >> c;
}
if (a+b<c || a+c<b || b+c<a)
{
cout << "That is not a valid triangle." <<endl;
cout << "Please re-enter three sides: " <<endl;
}
}
while(a+b<c || a+c<b || b+c<a);
perimeter= a+b+c;
cout << "The perimeter is: " << perimeter <<endl;
s=(a+b+c)/2;
area= sqrt(s*(s-a)*(s-b)*(s-c));
if (area==0)
cout << "The area cannot be zero." <<endl;
else
cout << "The area is: " << area <<endl;
cout << "Do you want to try again?" <<endl;
cout << "Choose [Y/N]" <<endl;
cin >> choice;
while (choice != 'y' && choice != 'Y' && choice != 'n' && choice != 'N'){
cout << "I do not understand. Try again: ";
cin >> choice;
}
} while (c == 'y' || c == 'Y');
return 0;
cin.ignore(); cin.ignore();
}
-
Because choice is a double and y is a char.
Btw, indent properly. Makes code easier to read.
-
edit: I'm wrong. Thanks Elysia.
Code:
while(a+b<c || a+c<b || b+c<a);
this loop? it's an infinite loop. the conditional never changes.
-
No, the syntax is correct - it's a do...while loop.
-
You're not handling some cases of invalid triangles such as 1, 2, 4.
-
incidently, try using more discriptive variable names rather than a,b,c etc. it stands out better what they represent and makes reading and espcially debugging the code a lot easier.
-
Although in this case, a, b and c are commonly used names for the sides of the triangle, and they are even used in the prompts for their values, so it's not that bad. The variable s, on the other hand, doesn't seem to be as self-explanatory.