Wednesday 18 June 2014

C++ program to evaluate cosine series

Here are C++ program to calculate cosine of the angle. First program calculate cosine of the angle using cos() function, second program evaluate cosine series(you can enter the accuracy for the result) and third program uses recursion to evaluate cosine series.


C++ program calculate cosine of the angle using cos() function

#include<iostream>
#include<math.h>
using namespace std;
int main()
{
    double y,temp,x;
    cout<<"Enter the value of x ";
    cin>>x;
    y=x;
    x=x*3.142/180;
    temp=cos(x);
    cout<<"cos("<<y<<") = "<<temp;
    return 0;
}




C++ program evaluate cosine series

#include<iostream>
#include<math.h>
using namespace std;
long double factorial(int n)
{
    long double fact=1;
    while(n>0)
    {
        fact*=n;
        n--;
    }
    return fact;
}
int main()
{
    float temp=1,x,z;
    int n,y=-1;
    cout<<"Enter the value of x ";
    cin>>x;
    cout<<"Enter the accuracy of the result ";
    cin>>n;
    z=x;
    x=x*22/(180*7);
    for(int i=2;i<=n;i+=2)
    {
         temp+=y*pow(x,i)/(1.0*factorial(i));
         y=-y;
    }
    cout<<"cos("<<z<<") = "<<temp;
    return 0;
}




C++ program evaluate cosine series using recursion

#include<iostream>
#include<iomanip>
#include<math.h>
using namespace std;
long double factorial(int n)
{
    long double fact=1;
    while(n>0)
    {
        fact*=n;
        n--;
    }
    return fact;
}
void coss(float &temp,int y,float x,int i,int n)
{
    if(i>n)
        return;
    temp+=y*pow(x,i)/(1.0*factorial(i));
    coss(temp,-y,x,i+2,n);
}
int main()
{
    float temp=1,x;
    int n;
    cout<<"Enter the value of x ";
    cin>>x;
    cout<<"Enter the accuracy for the result ";
    cin>>n;
    coss(temp,-1,x*22/(180*7),2,n);
    cout<<setprecision(3)<<"cos("<<x<<") = "<<temp;
    return 0;
}


No comments:

Post a Comment