-
Right sided triangle
Hey guys
I am trying an exercise in a book I found at the library and it asks me to write a program that reads three values and determines if they could make a right sided triangle.
I have made a fairly good attempt but I think my algorithm is a bit muddled. Can
you help me out.
The code below compiles ok.
Code:
#include <iostream>
#include <cmath>
// main function - driver //////////////////////////////////////////////////////
//
int main ( void )
{
double hypotenuse = 0,
sideA = 0,
sideB = 0,
squSideA = 0,
squSideB = 0,
totalSqu = 0;
std::cout << "Enter the hypotenuse: ";
std::cin >> hypotenuse;
std::cout << "Enter the sizes of the other two sides: ";
std::cin >> sideA >> sideB;
// find the square of each side
squSideA = sqrt ( sideA );
squSideB = sqrt ( sideB );
// get the total square of both sides
totalSqu = squSideA + squSideB;
if ( totalSqu == hypotenuse )
{
std::cout << "\nThis could represent a right-sided triangle\n";
}
else
{
std::cout << "\nThis could not represent a right-sided triangle\n";
}
std::cin.get(); // freeze console output window
std::cin.ignore();
return 0; // return value from int main
}
-
sqrt is the square root, the exact opposite of the square :) You want something like:
Code:
if ((hypotenuse * hypotenuse) == ((sideA * sideA) + (sideB * sideB))) {
// Woohoo
}
edit: This is the Pythagorean Theorem where a^2 + b^2 = c^2, where c is the hypotenuse.
QuantumPete
-
Thank you QuantumPete - great help. Thanks so much :)
-
It may also be a good idea to do your double comparison using a delta value or some such, to avoid problem where someone enters 0.3, 0.4, 0.5, and gets the answer that it isn't a triangle, when it in reality is, just that the 0.3 value turned into 0.2999999999 or some such.
--
Mats