We are required to make a c++ program to determining the cos of x by using the taylor series. i have made my program and it works pretty good but we are also required to stop the loop after the terms in the taylor series gets lower than .0001. any suggestions?
(Taylor Series for cos = 1 - x^2/2! + x^4/4!...)

#include <iostream>
#include <cmath>
using namespace std;

double fac(int n)
{
double f=n;
while (--n)f*=n;
return f;
}

int main()
{
double long x;
cout << "Enter Angle in Radians: " << endl;
cin >> x;
double cos(0.0);
double temp(0.0);

for (int i=0; i<170; i++){
if (i%2 == 1)
temp = (pow(x,i*2+2))/(fac(i*2+2));
else
temp = (-1)*(pow(x,i*2+2))/(fac(i*2+2));
if (temp <= 0.0001)
break;
else
cos += temp;
}

cout << "Cosine of Angle is: " << cos << endl;

system("PAUSE");
return 0;
}

I would use a while loop as in:

int i = 0;
while (temp < 0.0001) {
   temp = pow(-1,i) * (pow(x,i*2+2)) / (fac(i*2+2));
   cos += temp;
   i++;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.