I am making a program to tell the user what kind of triangle the sides entered make. How can I ensure they can only enter positive values. Using a loop or functions or something? All I can think of is to make separate do while loops for every variable. I also want the program to repeat again if the user wants to.
#include <iostream>
#include <math.h>
usingnamespace std;
int main ()
{
int a, b, c;
cout<<"Enter the length of side a:" << endl;
cin>>a;
cout<<"Enter the length of side b:" << endl;
cin>>b;
cout<<"Enter the length of side c:"<< endl;
cin>>c;
if(a==b && b==c)
cout << "Equilateral triangle (all sides are equal)\n";
elseif(a==b || a==c || b==c)
cout << "Isosceles triangle (only two sides are equal)\n";
elseif (pow(a,2) == pow(b,2) + pow(c,2) || pow(b,2) == pow(a,2) + pow(c,2) || pow(c,2) == pow(a,2) + pow(b,2))
cout << "This is a RIGHT triangle";
else
cout << "Other type of triangle (Not ISOSCELES, NOT RIGHT, and NOT EQUILATERAL)\n";
return 0;
}
Hi,
> How can I ensure they can only enter positive values.
Use an if-statement and a while-statement :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
int a = 0, b = 0, c = 0;
while(1)
{
cout << "Enter the length of side a: " << endl;
cin >> a;
cout << "Enter the length of side b: " << endl;
cin >> b;
cout << "Enter the length of side c: " << endl;
cin >> c;
if(a <= 0 || b <= 0 || c <= 0)
{
cout << "Invalid lengths for the triangle. Try again.\n\n";
continue;
}
break;
}
#include <iostream>
#include <cmath>
int input(char*);
int main()
{
while (true)
{
int a = input("Enter the length of side a: ");
int b = input("Enter the length of side b: ");
int c = input("Enter the length of side c: ");
if (a == b && b == c)
{
std::cout << "Equilateral triangle (all sides are equal)\n";
}
elseif (a == b || a == c || b == c)
{
std::cout << "Isosceles triangle (only two sides are equal)\n";
}
elseif (std::pow(a, 2) == (std::pow(b, 2) + std::pow(c, 2)) ||
std::pow(b, 2) == (std::pow(a, 2) + std::pow(c, 2)) ||
std::pow(c, 2) == (std::pow(a, 2) + std::pow(b, 2)))
{
std::cout << "This is a RIGHT triangle\n";
}
else
{
std::cout << "Other type of triangle (Not ISOSCELES, NOT RIGHT, and NOT EQUILATERAL)\n";
}
std::cout << "\nWant to try again? (y or n): ";
char again;
std::cin >> again;
if (again != 'y' && again != 'Y')
{
break;
}
std::cout << "\n";
}
}
int input(char* question)
{
int in = 0;
while (true)
{
std::cout << question;
std::cin >> in;
if (in < 0)
{
std::cout << "Invalid input, number must be positive!\n";
}
else
{
break;
}
}
return in;
}
Enter the length of side a: 5
Enter the length of side b: 5
Enter the length of side c: 5
Equilateral triangle (all sides are equal)
Want to try again? (y or n): y
Enter the length of side a: -15
Invalid input, number must be positive!
Enter the length of side a: 25
Enter the length of side b: 5
Enter the length of side c: 25
Isosceles triangle (only two sides are equal)
Want to try again? (y or n): n