You are here:

- Home
- Computing/Technology
- C/C++
- C++
- while loop Question ??

Advertisement

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

//200758855

#include <iostream.h>

int main ()

{

double x , f=1 , n ,i ,r ,s=0;

cout<<"Enter a number";

cin>>n;

x=1;

while (x<=n)

{

f=f*x;

i=0 ;

while (i<=x)

{

r=n/f;

i++;

}

s=s+r;

x++;

}

cout<<"e="<<s;

return 0;

}

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

increment cnt

#include <iostream>

//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 ;

cnt++;

}

std::cout << "e=" << sum << '\n' ;

}

my primary areas of interest are generic and template metaprogramming, STL, algorithms, design patterns and c++11. i would not answer questions about gui and web programming.

about 15 years or so**Education/Credentials**

post graduate engineer