To expand on the title of the thread, I have been having trouble creating a proper cosine function that uses recursion. I don't want to use any form of a loop in this code. I have tried everything I can think of to accomplish this, but I haven't had any luck so far. Here is the code:
The safeChoice() function is not necessary to understand my problem, so I haven't included it in the code I put here.
I also need to figure out how to not make main() recursive, as someone told me that just uses up memory every time the user enters a letter to fit that condition.
I have searched Google for about a week now to find an answer; still no luck from that. I basically need to understand why the code I have isn't working, and to understand how to fix it.
#ifndef M_PI
#define M_PI 3.141592653589793238462643383279502884197169399
#endif
#include <iostream>
#include <cmath>
#include <iomanip>
#include <sstream>
using namespace std;
long long factorial(long long num);
long double cosine(long double angle);
double constrainAngle(double x);
char safeChoice(string prompt, char choice1, char choice2);
const double CUT_OFF = 0.0001;
const int BUFFER_SIZE = 256;
int main(void)
{
long double angle = 0.0;
long double radAngle = 0.0;
long double c = 0.0;
char ch;
string deg = " ";
cout << "Input an angle in radians: ";
cin >> angle;
if (!cin.fail())
{
deg = angle == 1 ? " degree" : " degrees";
cout << "The cosine() approximation at " << angle
<< deg << " is equal to: " << setprecision(3)
<< cosine(angle) << endl;
cout << setprecision(3)
<< "The cos() function in the cmath library for this angle returns: "
<< cos(angle) << endl;
cin.get();
cout << endl;
cin.get();
ch = safeChoice("Calculate another cosine?", 'Y', 'N');
cout << endl;
if (tolower(ch) == 'n')
{
return EXIT_SUCCESS;
}
else
{
main();
}
}
else
{
cin.clear();
cout << "That is not a number. Press enter." << endl;
cin.get();
cin.get();
main();
}
}
long long factorial(long long num)
{
if(num < 0LL)
throw exception();
long long temp;
if(num <= 1LL)
return 1LL;
temp = num * factorial(num - 1);
return temp;
}
long double cosine(long double angle)
{
static int n = 0;
static long double sum = 0.0;
if(fabs(n) >= CUT_OFF)
{
n++;
sum += (pow(angle, n * 2) / factorial(2 * n));
cosine(angle);
}
else
{
return sum;
}
}
double constrainAngle(double x)
{
x = fmod(x, 2 * M_PI);
if (x < 0)
x += (2 * M_PI);
return x;
}
The safeChoice() function is not necessary to understand my problem, so I haven't included it in the code I put here.
I also need to figure out how to not make main() recursive, as someone told me that just uses up memory every time the user enters a letter to fit that condition.
I have searched Google for about a week now to find an answer; still no luck from that. I basically need to understand why the code I have isn't working, and to understand how to fix it.