Thursday, 20 October 2016

7.b Write a C Program to compute the values of cos x value using Series expansion


#include<stdio.h>
#include<math.h>
#define PI 3.1415


double cos_x( int, int );
int fact( int );

int main()
{
    int choice, x, n;


                    printf( "cos(x)\nEnter x and n:\t" );
                    scanf( "%d %d", &x, &n );
                    printf( "\ncos(%d)(%d) = %f\n", x, n, cos_x( x, n ) );

}


double cos_x( int ang_deg, int no_of_terms )
{
    int term, j;
    double value = 1.0, ang_rad = 0.0;
    ang_rad = ( double ) ang_deg * PI / 180;

    for ( term = 2, j = 1;term <= no_of_terms;term += 2, j++ )
        {
            value += ( double ) pow( -1, j ) * pow( ang_rad, term ) / fact( term );
        }

    return value;
}

int fact( int num )
{
    int f = 0;

    if ( num == 1 )
        return 1;
    else
 f = num * fact( num - 1 );

    return f;
}

No comments:

Post a Comment