Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Function prototype

  1. Oct 8, 2008 #1
    I am a beginner trying to enter a function prototype into C++. This is what I have entered....where am I going wrong?

    double f(double x)
    {
    return 5*pow(x,3)-3*pow(x,2)+2*x+1;
    }

    I would like to be able to enter something like f(2.4) later in the code, and have it calculate the value using this function. How would I do this?

    f(x)=5x3-3x2+2x+1
     
  2. jcsd
  3. Oct 8, 2008 #2

    KTC

    User Avatar

    There's nothing wrong with what you have.

    Code (Text):
    #include <iostream>
    #include <math>

    double f(double x)
    {
        return 5*std::pow(x,3) - 3*std::pow(x,2) + 2*x + 1;
    }

    int main()
    {
        std::cout << f(2.4) << std::endl;
    }
     
     
  4. Oct 9, 2008 #3
    OK, thanks. I didn't know I had to declare it before main().
     
  5. Oct 9, 2008 #4

    rcgldr

    User Avatar
    Homework Helper

    You don't have to define a function before it's called, just declare a prototype. Same code with an actual prototype:
    Code (Text):
    #include <iostream>
    #include <math>

    double f(double x);    /* this is the prototype */

    int main()
    {
        std::cout << f(2.4) << std::endl;
    }

    double f(double x)
    {
        return 5*std::pow(x,3) - 3*std::pow(x,2) + 2*x + 1;
    }
     
  6. Oct 9, 2008 #5

    Borek

    User Avatar

    Staff: Mentor

    Side note: while it is not generally an error, using pow function to raise float number to an integer power is an overkill. It is absolutely enough to use multiplication:

    Code (Text):
    5*x*x*x-3*x*x+2*x+1
    It will execute faster then your code. But it can be very simply modified to be executed even faster:

    Code (Text):
    x*(x*(5*x-3)+2)+1
     
  7. Oct 9, 2008 #6
    Thank you all for your help.
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?



Similar Discussions: Function prototype
  1. Fortran - Functions (Replies: 0)

  2. Functions in c (Replies: 1)

  3. Functions and arrays. (Replies: 1)

Loading...