Kumar - 1 month ago 14

C Question

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);

printf("\nYour value is\n %f",y);

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;

}

Any suggestion will helpful.

Answer

The formula expects values in radians but you're using integers so I'm assuming you give it degrees. That will make the formula give wrong values.

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.