- #1
okkvlt
- 53
- 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();
}
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();
}