My assignment is to write a program that estimates the value of the mathematical constant e by using the formula e = 1 + 1/1! + 1/2! + 1/3! +...
I asked for help from a classmate and they sent me there code so now I have the answer but it doesn't help since I don't understand why it works. Could someone please explain to me what this program does and why it works so that I can figure out how to write it myself.
#include <iostream>
#include <iomanip>
using namespace std;
// Lab2 Exercise 4B
// Find the accuracy of e
#include <iostream>
using namespace std;
int main()
{
int accuracy = 1;
int factorial = 1;
int counter = 1;
double e = 1.0;
I guess the first thing I don't understand is why the while statement is
while(counter <=(accuracy-1)) and how I would know to come up with that.
Is that statement saying that you want to repeat the e= e + (1/static_cast<double>(factorial)) from 1/1! until you get to the accuracy -1 so if you put in 5 for the accuracy it's going to repeat until it gets to 1/5! and then that is the answer?
The variable 'accuracy' is actually used to determine the number of terms to calculate in the series. You can probably understand it better if you think of this variable as 'terms to calculate' instead.
The while loop condition is counter <= accuracy - 1 because the initialized value of 'e' is 1, which happens to be the first term in the series. If you wanted to find the value of e using 5 terms, your while statement needs to loop 4 times, since the first term(loop) is already defined.
Thank you so much. I didn't want to just except the answer and not understand it since I will have to produce hand written programs on my mid-term and final without using a computer or other forms of help.