Click here to Skip to main content
15,885,366 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i am writing this program to calculate the value of (e) using this formula (1+1/1(1+1/2(1+1/3(1+1/4)))
i have this so far but im getting the answer as 1.71828 and its supposed to be 2.71828 when 100 is plugged in . i appreciate any help.

C++
# include <iostream>
using namespace std;

void main ()
{
double n;
cout<<"please input number:";
cin>>n;
double m=1.0+1.0/n;
int i=n-1;

while (i>0){
	m=1.0+1.0/(m*i);
	--i;
		}
	
cout<<"number is "<<m<<endl;
}
Posted
Updated 24-Jan-10 19:34pm
v4

Hi!! :) Replace the line:
<br />
m=1.0+1.0/(m*i)<br />


with this one:
<br />
m = m / i + 1;<br />

regards!

P.S.
But, I suggest you to pay attention to Avi's answer. :)
 
Share this answer
 
v2
You are working from the inside out in your formula, which looks to be like the best way to approach it. You aren't getting your formula coded right though.

Your formula for level n is 1 + (1/n)( value for level n + 1 ).

Now look at what you actually coded on the line in bold.

nfavenom wrote:

void main ()
{
    double n;
    cout << "please input number:";
    cin >> n;
    double m = 1.0 + 1.0 / n;
    int i=n-1;

    while (i>0){
        m = 1.0 + 1.0/(m*i);
        --i;
    }

    cout<<"number is "<<m<<endl;
}


There are also a few other problems with this code as well, so once you fix the line in bold, you aren't done.

In particular:

1) You have the signature for main() wrong - check C++ documentation for what valid signatures for main() are,

2) n is of the wrong type and should be merged with one of your other variables,

and

3) not all values that the user might enter are appropriate. What values are not appropriate? What currently happens if the user enters such a value? How about doing something to deal with this.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900