Calculating Hypotenuse with C++ Code

  • Thread starter Thread starter magnifik
  • Start date Start date
  • Tags Tags
    Code Triangle
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
6 replies · 2K views
magnifik
Messages
350
Reaction score
0
i am trying to write a code that calculates the hypotenuse of a triangle... when i try to run it, i get a run time error. I'm not exactly sure what the problem is.

Code:
 #include <iostream>
    #include <cmath>
    using namespace std;

    void hypotenuse(double side1, double side2, double* result)
    {
        *result = sqrt(side1*side1 + side2*side2);
    }

    int main()
    {
        double* p;
        hypotenuse(1.5, 2.0, p);
        cout << "The hypotenuse is " << *p << endl;
    }
 
on Phys.org
nvm, figured it out. i just had to initialize p to new double.
 
Something like this?
Code:
int main()
{
    double answer;
    double* p = &answer;
    hypotenuse(1.5, 2.0, p);
    cout << "The hypotenuse is " << answer << endl;
}

This works for me, and produces the correct result.
 
i just did

Code:
int main()
{
double* p;
p = new double;
hypotenuse(1.5, 2.0, p);
cout << "The hypotenuse is " << *p << endl;
delete [] p; // i know this part is unnecessary though
}
 
A much simpler approach is this code in main - no changes needed in hypotenuse:
Code:
double answer; 
hypotenuse(1.5, 2.0, &answer);
cout << "Hypotenuse is " << answer << endl;
return 0;

You can initialize answer, but that's not really necessary, since it will be overwritten.