In: Computer Science
The cosine of an angle can be computed from the following infinite series: cosx=1-(x^2/2!)+(x^4/4!)-(x^6/6!)+......
Write a program in C++ that reads an angle x (in radians) from the keyboard. Then, in a function compute the cosine of the angle using first five terms of the series. Print the value computed along with the value of the cosine computed using the C++ library function.
#include <iostream>
#include <math.h>
using namespace std;
float calculatedCos(float x){
float accuracy = 0.0001;
//calculate to radians from degrees
x = x * (3.142 / 180.0);
float cosval = cos(x);
float x1,cosx,denominator;
x1 = 1;
cosx = x1;
int i = 1;
do
{
denominator = 2 * i * (2 * i - 1);
x1 = -x1 * x * x / denominator;
cosx = cosx + x1;
i = i + 1;
} while (accuracy <= fabs(cosval - cosx));
return cosx;
}
int main() {
float x;
cout<<"x: ";
cin>>x;
cout<<"\nCalculated cos("<<x<<") : "<<calculatedCos(60)<<endl;
float x60radians = 60*(3.14/180.0);
cout <<"\n Actual cos("<<x<<") : "<<cos(x60radians)<<endl;
}