-2

I want to call a function to calculate Pythagoras and to see whether it is true that a triangle is a right angled triangle using three inputs. I am very new to C++ and will appreciate help with this:

This is my code, it runs but does not work correctly:

    #include <iostream> 
#include <cmath> 

using namespace std;

double pythagorusTheorem(double a, double b, double c);

int main(){

double a;
double b;
double c;

cout << "Write the three sides of the triangle, enter biggest first and shorter sides after: " << endl;

cin >> a >> b >> c; 



if (double val=pythagorusTheorem(a,b,c) == true){

cout << "This is a right-angle triangle " << endl;

}

if (double val=pythagorusTheorem(a,b,c) == false) {

cout << "This is not a right angled triangle " << endl; 

}

return 0;
}


double pythagorusTheorem(double a, double b, double c){

a = pow(b,2) + pow(c,2);



}

2 Answers2

1

You don't return a value from pythagorusTheorem. This is undefined behaviour. In addition:

if (double val=pythagorusTheorem(a,b,c) == true)

...reaaaally doesn't do what you expect. Remember that == is for comparing if two values are equal, but = is for assigning a value to a variable.

You'd be much better suited by changing the function to one which returns true or false depending on if your values fulfill the required condition:

bool pythagorasTheorem(double a, double b, double c)
{
    return a*a == b*b + c*c;
}

Then change your comparisons to:

if (pythagorasTheorem(a,b,c))
{
    cout << "This is a right-angle triangle " << endl;
}

I have to refer you to this lovely list of C++ books - you should read up on functions, in particular. This will likely also be helpful.

hnefatl
  • 5,860
  • 2
  • 27
  • 49
  • Given this, you just need to say `if (pythagorusTheorem(a, b, c))`; you *almost never* need to compare to `true` or `false` explicitly. – Daniel H Oct 22 '17 at 18:53
  • 1
    @DanielH Caught me mid-edit, sorry... – hnefatl Oct 22 '17 at 18:54
  • Multiplication is more efficient than calling the `pow` function, so `a * a` would be more efficient than `pow(a, 2)`. – Thomas Matthews Oct 22 '17 at 19:01
  • @ThomasMatthews Yeah, I was trying to stay in the vein of the original code. I'll edit though, as I suppose I've ripped enough of OP's original code up anyway. – hnefatl Oct 22 '17 at 19:02
0

If you write your function like this:

bool pythagorasTheorem(double a, double b, double c)
{
    a *= a;
    b *= b;
    c *= c;
    return a == b + c || b == c + a || c == a + b;
}

using @hnefatl solution, you don't have to enter longest side first

Killzone Kid
  • 6,171
  • 3
  • 17
  • 37