1. Not finding help here? Sign up for a free 30min tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Hyp of a triangle using code

  1. May 25, 2010 #1
    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 (Text):
     #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;
        }
     
  2. jcsd
  3. May 25, 2010 #2

    Mark44

    Staff: Mentor

    I don't see anything obvious, although your main should return a value. What's the run-time error?
     
  4. May 25, 2010 #3
    nvm, figured it out. i just had to initialize p to new double.
     
  5. May 25, 2010 #4

    Mark44

    Staff: Mentor

    Something like this?
    Code (Text):

    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.
     
  6. May 25, 2010 #5
    i just did

    Code (Text):
    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
    }
     
  7. May 25, 2010 #6

    Mark44

    Staff: Mentor

    Well, that's one way. At the end you can just delete p since it's not an array.
     
  8. May 25, 2010 #7

    Mark44

    Staff: Mentor

    A much simpler approach is this code in main - no changes needed in hypotenuse:
    Code (Text):

    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.
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: Hyp of a triangle using code
Loading...