I just found the answer to this question on the net but I'm unable to run it.
Code:
#include <stdio.h>
#include <math.h>
double sinEst(double,unsigned);
typedef double (*func)(double,double);
double add(double,double);
double subtract(double,double);
double factorial(unsigned);
const double PI = 3.1415926535897932384626433832795028841;
typedef struct
{
func f[2];
double k;
} Op_t;
int main(int argc, char *argv[]) {
unsigned n;
double x,xRad,sinX;
if ((argc < 3) ||
(sscanf(argv[1],"%lg",&x) != 1) ||
(sscanf(argv[2],"%u",&n) != 1)) {
printf("usage : %s <x>,<n>\n",argv[0]);
printf(" where <x> = angle for sin estimate, in degrees\n");
printf(" <n> = number of terms, a positive integer\n");
return -1;
}
xRad = x * PI / 180.0;
sinX = sinEst(xRad,n);
printf("\nnumber of terms in series = %u",n);
printf("\nestimated sin(%g) = %g",x,sinX);
printf("\nactual sin(%g) = %g",x,sin(xRad));
getch();
return 0;
}
double sinEst(double x, unsigned numTerms) {
double sinX = x;
Op_t op;
unsigned i;
op.f[0] = add;
op.f[1] = subtract;
op.k = 3;
for (i = 1; i < numTerms; i++, op.k += 2) {
sinX =
op.f[i%2]( sinX,pow( x,op.k ) /
factorial( (unsigned)op.k ) );
}
getch();
return sinX;
}
double factorial(unsigned n) {
if (n == 1) return n;
return n * factorial(n-1);
}
double add(double a,double b) { return a + b; }
double subtract(double a,double b) { return a - b; }
This is my output:
usage : lab5c.exe <x>,<n>
where <x> = angle for sin estimate, in degrees
<n> = number of terms, a positive integer