How do i declare a function in the command promp window (c++ question)

  • Context: C/C++ 
  • Thread starter Thread starter okkvlt
  • Start date Start date
  • Tags Tags
    Function Window
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
1 reply · 2K views
okkvlt
Messages
53
Reaction score
0
Hi. i wrote a script that finds the definite integral of a function using simpsons rule.
right now the function to be integrated is defined as 2*pow(9-pow(x,2),.5).
but this is very inconvenient to me because i must edit the program each time i want to find a new integral. my question is how do i define the function to be integrated inside the command prompt window? (in other words, i want the user to declare the function to be integrated, instead of the programmer declaring the function to be integrated.)




#include <stdio.h>
#include <math.h>
/*define f[x]*/
double f(double x)
{
double f=2*pow(9-pow(x,2),.5) ;
return f;
}

/*program main*/

int main()
{
double a,b,dx;
long double total1=0,total2=0;
long int n,i=1;
printf("b\nS f[x]dx\na\n\n");
printf("b=");
scanf("%lf",&b);
printf("a=");
scanf("%lf",&a);
printf("number of increments=");
scanf("%d",&n);
dx=(b-a)/n;
printf("%.13lf\n",dx);
/*calculations*/
while(i<=n-1)
{
total1=dx*f(a+i*dx)+total1;
printf("%d\r",i);
i=i+1;
}
i=0;
while(i<=n-1)
{
total2=dx*f(a+(i+.5)*dx)+total2;
printf("%d\r",i);
i=i+1;
}
double integral=total1/3+2*total2/3+dx*(f(a)+f(b))/6;

printf("definite integral=%.13lf", integral);
getchar();
getchar();
}
 
Physics news on Phys.org
You can pass a string as an argument to your main function, and your program will need to be able to parse the string to figure out what the function is. Look up "arguments to main" to find out how that works. Parsing the string that is passed into main is quite a bit more complicated because your program will have to have logic so that it understands the arithmetic operators (+, -, *, /), powers of functions, trig functions, and whatever else your program needs to work with.