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

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

  1. Dec 12, 2009 #1
    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();
    }
     
  2. jcsd
  3. Dec 14, 2009 #2

    Mark44

    Staff: Mentor

    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.
     
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook