Reputation: 45
In the following code I try to calculate sin(x)
by adding the first N
terms of the infinite series.
#include <stdlib.h>
#include <math.h>
#define pi 3.14
int main()
{
float sign=-1,d,x,n,k,factorial=1,y;
printf("Enter the degree ");
scanf("%f", &d);
printf("Enter num of terms ");
scanf("%f", &n);
x = d * pi / 180 ;
for(int i=0,j=1 ; (i==n) && (j<=y) ; i++,j++){
y = 2*i + 1 ;
factorial *= j ;
sign = - 1 * sign ;
k += sign * pow(x,y) / factorial ;
}
printf("%f",k);
}
The problem is that the output is always 0.00000
.
Q: Why does calculating sin(x) by adding the first N terms of an infinge series always return 0.00000?
Upvotes: 1
Views: 110
Reputation: 226346
The (i==n) && (j<=y)
line is always false, so the loop never runs.
#include <stdio.h>
#include <math.h>
#define pi 3.1415926536
int main()
{
float d, x, estimate=0.0, factorial=1.0, sign=1.0;
int i, n;
printf("Enter the degree ");
scanf("%f", &d);
printf("Enter num of terms ");
scanf("%d", &n);
x = d * pi / 180;
for (i=1 ; i<=2*n ; i+=2) {
estimate += sign * pow(x, i) / factorial;
factorial *= (i+1) * (i+2);
sign = -sign;
printf("%f\n", estimate);
}
return 0;
}
Upvotes: 3