Kumar - 3 years ago 211
C Question

# How to create a sine function in c

I know their is a sin function in math.h but I want to make that function at my own, just for fun. I have created sin function based on Macluarin expansion of the sine function.

I write power function and factorial function, they work correctly from int main,but they do not work in sin function, here is my code

``````int main()
{
int i;
double y;
printf("\n\nPlease enter a value to find corresponding sin value\n");
scanf("%d",&i);
y=sin(i);
return 0;
}

double sin(int z)
{
int i=1;
double value,val2,val3,sum=0;
for(i=1;i<33;i+=2)
{
val2=power(z,i);
val3=factorial(i);
value=val2/val3;
if(((i-1)/2)%2!=0){
sum=sum-value;    //((power(x,i))/factorial(i));
}else
{
sum=sum+value;
}
}
printf("\n%f\n",sum);
return sum;
}

int factorial(int x)
{
int i,sum=1;
for(i=1;i<=x;i++)
{
sum = sum*i;
}
return sum;
}

int power(int x,int y)
{
unsigned long long int i,sum=1;
for(i=1;i<=y;i++)
{
sum=sum*x;
}
return sum;
}
``````

Also you use `int`s as return values from `factorial()` and `power()` which will cause overflows. If you have 32bit machine even giving 2 to your formula will overflow since `int` can only go up to 2^31-1 and your trying to get 2^33.
Also if your compiler doesn't complain that you're returning an `unsigned long long int` from a function that has `int` as a return type please increase the warning level.