Calculating Hypotenuse with C++ Code

  • Thread starter Thread starter magnifik
  • Start date Start date
  • Tags Tags
    Code Triangle
AI Thread Summary
The discussion focuses on resolving a runtime error encountered while calculating the hypotenuse of a triangle using C++. The initial code fails because the pointer `p` is uninitialized, leading to undefined behavior. Solutions include initializing `p` with `new double` or using a local variable like `answer` and passing its address to the `hypotenuse` function. The simpler approach is preferred, as it avoids unnecessary memory allocation. The final consensus is that initializing a local variable is sufficient for the calculation without the need for dynamic memory management.
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;
    }
 
Physics news on Phys.org
I don't see anything obvious, although your main should return a value. What's the run-time error?
 
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
}
 
Well, that's one way. At the end you can just delete p since it's not an array.
 
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.
 

Similar threads

Replies
2
Views
3K
Replies
15
Views
7K
Replies
3
Views
1K
Replies
8
Views
1K
Replies
15
Views
2K
Replies
15
Views
3K
Replies
1
Views
2K
Back
Top