1

I need to create my own function to compute the cos of an angle (given in radians) using the Taylor series. The task is to create a function in which a float value is passed to it, and a double gets returned. My program compiled, but I am getting wrong values.

If my input were 2, then I would get 20.987860

The answer I need is cos(2pi) = 2

Here's my code:

```
#include <stdio.h>
#define DEBUG
float cosi(float x);
int factorial(int x);
main()
{
/* Declarations */
double pi = 3.14159;
float input;
double rad;
double cosine;
/* Ask user for an angle (in radians) */
printf("Enter an angle in rads (don't include pi): ");
/* While user has more input */
while ( scanf("%f", &input) != EOF)
{
/* Convert input into its decimal form */
rad = input * pi;
#ifdef DEBUG
printf("debug: rad = %f\n", rad);
#endif
/* Call cosine function */
cosine = cosi(rad);
/* Print result */
printf("The cosine value is: %f\n", cosine);
/* Update loop */
printf("Enter an angle (in radians): ");
}
}
float cosi(float x)
/* Given : an angle in radians (float)
* Returns: the cosine value of the angle
*/
{
/* Declare variables */
int i,fact=1;
float sum,term;
/* Initialize at 1 */
sum=1.0;
term=1.0;
for(i=1;i<5;i++)
{
term *= -x * x;
#ifdef DEBUG
printf("term = %f\n", term);
#endif
fact=factorial(2*i);
#ifdef DEBUG
printf("factorial = %d\n", fact);
#endif
sum=sum+(term/fact);
#ifdef DEBUG
printf("sum = %f\n", sum);
#endif
}
return(sum);
}
int factorial(int x)
/* Given : a multiple of 2
* Returns :the value of */
{
int fact;
if(x==1)
return(1);
else
fact=x*factorial(x-1);
return(fact);
}
```

Does anyone see where I went wrong?