#include <iostream>
#include <cstdlib>
#include <cmath>
#include <iomanip>
usingnamespace std;
// Define prototypes
int factorial(int);
int sum(double, int);
int main()
{
// Initialize variables
double x;
int n;
cout << "\nThis program calculates the value of cosine using the McLaurin Series Expansion.\n";
cout << "Please enter a value for x that is in the range (-3.14, 3.14).\n";
cout << "> ";
cin >> x;
cout << "Please enter the number of terms.\n";
cout << "> ";
cin >> n;
factorial(n);
cout << sum(x, n);
return 0;
}
// Factorial function
int factorial(int n)
{
cout << fixed << showpoint << setprecision(3);
for(int i = 1; i == n; i++)
{
return n *= i;
}
}
// Sum function
int sum(double x, int n)
{
cout << fixed << showpoint << setprecision(3);
for (int i = 0; i == n; i++)
{
if (i % 2 == 0)
{
return 1 - pow(x, (2 * n)) / factorial(2 * n);
}
elseif (i % 2 != 0)
{
return pow(x, (2 * n)) / factorial(2 * n);
}
}
}
On the 1st loop you multiply term by -x*x/(1*2) and you add it to sum.
On the 2nd loop you multiply term by -x*x/(3*4) and you add it to sum.
On the 3rd loop you multiply term by -x*x/(5*6) and you add it to sum.
...
On the rth loop you multiply term by -x*x/((2r-1)*(2r) and you add it to sum.
Spot the pattern?
You should NEVER evaluate the sign term by using pow() here - it is pointless.
You should NEVER evaluate factorial as a function here: it is inefficient, pointless, and will probably blow up.
Your factorial and sum functions has some issues. You make similar mistakes in both of them
(1) You are always returning during the first iteration -- you have a return statement in all branches of each for loop iteration.
(2) Your ending condition for your for loopis i == n. You probably want "i < n" or similar.
Also, your sum function should be returning a double, since I assume you don't want whole numbers to be the only possible answers.