C++/while loop Question ??
Write a program that estimates the value of the mathematical constant e by using the formula:
e = 1 + 1/1! + 2/2! + 3/3! + 4/4! + ………+ n/n!
Here is what i've done::
//Sarah Jamal Qaffaf
int main ()
double x , f=1 , n ,i ,r ,s=0;
cout<<"Enter a number";
Can you tell me what I'm doing wrong??
indent your code. makes it much easier to read and modify.
unless you are using an obsolete compiler, do not use <iostream.h>. it is not part of standatd C++. instead write: #include <iostream> ; and if you want, using namespace std ;
use appropriate variable types. eg. int for integer values
give meaningful names to variables. for example:
int cnt - the number of terms evaluated so far
int max_cnt - the total number of terms to be evaluated
double factorial - factorial of cnt
double term - the term in the series ie. cnt / factorial
double sum - sum of the terms in the series; at the end, it becomes (approximately) the mathematical constant 'e'
you require only one loop, not two.
each time through the loop:
evaluate the new factorial - (previous) factorial * cnt
compute the term - cnt / factorial
add the term to the sum - sum = sum + term
//using namespace std ;
int main ()
int cnt = 1 , max_cnt ;
double factorial = 1.0 , sum = 0.0 ;
std::cout << "Enter a number " ;
std::cin >> max_cnt ;
while ( cnt <= max_cnt )
factorial = factorial * cnt ;
double term = cnt / factorial ;
sum = sum + term ;
std::cout << "e=" << sum << '\n' ;