There are several errors. For instance
Quote:
for(i=1;i<=n;i+2)
is wrong, the last statement in the for clause ha no effect, it should be
i+=2
. Moreover, the
fact
variable must be initialized immediately before the factorial loop (by the way, it is better using a
float
variable for holding the factorial result, because it becomes large soon).
You might fix your code this way:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
int i,j,n,ch,p;
float fact;
float x,sum,angle;
do
{
printf("\n1. Sine series\n2. Cosine series\n3. Exponential series\n4. Exit\nEnter your choice: ");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("\nEnter the value of x(in degree)and n in sine series.\n");
scanf("%f",&x);
scanf("%d",&n);
angle = x;
x=x*M_PI/180;
sum=0.0;
p=0;
for(i=1;i<=n;i+=2)
{
fact=1;
for(j=2;j<=i;j++)
{
fact=fact*j;
}
sum+=(pow(-1,p)*((float)pow(x,i)/fact));
p++;
}
printf("\nsin(%.2f)=%.2f\n",angle,sum);
break;
However I would factor out the
sin
computation in a function, and I would also compute the terms incrementally, e.g.
#include <stdio.h>
#include <math.h>
double comp_sin( double x, int n)
{
double sign = 1.0;
double fact = 1.0;
double sum=0.0;
double x2 = x * x;
int k;
for (k=0; k<n; ++k)
{
sum += (sign * x) / fact;
sign = sign > 0.0 ? -1.0 : 1.0; fact *= (2.0 * k + 2.0) * (2.0 * k + 3.0); x *= x2; }
return sum;
}
int main()
{
int n;
double angle;
printf("please enter the angle in degres and the number of terms of the series\n");
scanf("%lf", &angle);
scanf("%d", &n);
printf("sin(%g) = %g\n", angle, comp_sin(angle*M_PI/180, n ));
return 0;
}