Creating a Function Prototype in C++ to Calculate a Value Using f(x)

  • Context: C/C++ 
  • Thread starter Thread starter Freyster98
  • Start date Start date
  • Tags Tags
    Function Prototype
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
5 replies · 3K views
Freyster98
Messages
49
Reaction score
0
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
 
Physics news on Phys.org
There's nothing wrong with what you have.

Code:
#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;
}
 
OK, thanks. I didn't know I had to declare it before main().
 
You don't have to define a function before it's called, just declare a prototype. Same code with an actual prototype:
Code:
#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;
}
 
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:
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:
x*(x*(5*x-3)+2)+1
 
Thank you all for your help.