Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

I know the code is simple, but how do I make it work?

+9 votes
asked Jan 9 by Alexandr (300 points)
double mycos(double x,double eps)
    double s,an;
    int n;
    return s;

1 Answer

+6 votes
answered Jan 9 by Peter Minarik (63,180 points)
selected Jan 10 by Alexandr
Best answer

What do you mean by "make it work"?

Using your function in the following scenario seems to work.

#include <stdio.h>
#include <math.h>

#define PI 3.1415926535897932384626433832795

double mycos(double x, double eps)
    double s = 0.0
    double an = 1.0;
    int n = 0;
    while (fabs(an) > eps)
         s += an;
         an *= - x * x / (2.0 * n - 1.0) / (2.0 * n); 
    return s;

int main()
    printf("cos(60) = %lf\n", mycos(PI / 3, 0.1));
    return 0;

And the result is

cos(60) = 0.451689

It seems to be more or less correct (with a certain error level).

You can test it with various inputs and see where it makes mistakes (for instance instead of using PI / 3 radians, using 60 radians returns a wrong value). (Note: first I thought it calculates in degrees, hence I used 60 radians -- which I wrongly thought was 60 degrees and that's how I found this input to produce erroneous output.)

Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.