I have the code for the first part of a problem, which is to write a program that reads an angle x (in radians) from the keyboard. Then, in a function, compute the cosine of the angle using the first five terms of this series. Print the value computed along with the value of the cosine computed using the C++ library function.
However, I need help modifying the program so that the approximation uses terms from the series as long as the absolute value of a term is greater than 0.0001. Also, print the number of terms used in the series approximation.
I am new to programming and appreciate any help. Thanks!
// Pre-processor Directives
#include<iostream> // Required for for use of cin, cout
#include<cmath> // Required for use of sin, cos, pow functions
// using directives
using namespace std;
// PROGRAM STARTS HERE!
double cosine(double angle);
long factorial(long n);
// Declaration of the main function
int main()
{
double angle;
// Ask for user input
cout << "Enter the angle in radians: ";
cin >> angle;
// Display the result
cout << "The calculated cosine of " << angle << " is " << cosine(angle) << endl;
cout << "The C++ cosine of " << angle << " is " << cos(angle) << endl;
// Exit program.
system("PAUSE");
return 0;
}
double cosine(double angle)
{
// Declare the variables
double x=0;
double i;
/* formula
x = 1 - pow(angle, 2)/factorial(2) + pow(angle, 4)/factorial(4) -
pow(angle, 6)/factorial(6) + pow(angle, 8)/factorial(8);*/
// For Loop
for (i=2; i<=8; i+=2)
{
if (i==4 || i==8)
{
x = x + pow(angle, i)/factorial(i);
}
else
{
x = x - pow(angle, i)/factorial(i);
}
}
return 1+x;
}
long factorial(long n)
{
if (n <= 1)
{
return 1;
}
else
{
return (n * factorial(n-1));
}
}