Thread: approx value of (e)/

  1. #1
    Registered User o0o's Avatar
    Join Date
    Dec 2003
    Posts
    37

    Thumbs down approx value of (e)/

    Value of e is to be found by the formula

    e=1+1/1!+1/2!+1/3!+..................

    The following code give value only upto 5!.Although it should increment num and use the new value (ie 5!*6!*7!*..........)again.What's wrong?

    Code:
    #include<iostream>
    #include<conio.h>
    
    using std::cout;
    using std::cin;
    using std::endl;
    
    int main()
    {
        // declare and initialize variable/s
        
        int num=5,factorial=1;
        double result;
        
        // display the approx value of e
        
        while(num>0)
        {
            factorial=factorial*num;
            num-=1;
            result=1+factorial;
        }
        
        cout<<"\n\n\t\t\te = "<<1/result;
        num+=1;
        
    getch();
    }

  2. #2
    Registered User
    Join Date
    Jun 2003
    Posts
    361
    You're setting:
    num=5

    Then, in your While Loop, the condition is:
    while (num > 0)

    And inside your loop, you are decreasing num by 1 each time.
    Meaning the first time around, num = 5.
    Then 4,
    then 3,
    then 2,
    then 1,
    then, it equals 0, and since 0 (Num) is not greater than 0 (Your Condition), it exits the loop. Hence, only doing it 5 times.

  3. #3
    Registered User
    Join Date
    Oct 2002
    Posts
    291
    Does this help :
    Code:
    #include<iostream>
    #include<conio.h>
    
    using namespace std;
    
    int func(int number)
    {
        if(number > 0)
            return number * func(number-1);
        
        return 1;
    }
    
    int main()
    {
        cout << "5! = " << func(5) << endl;
        getch();
    }
    Last edited by laasunde; 12-25-2003 at 02:31 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. I Need Help Defining and Calling Functions
    By jonbuckets in forum C++ Programming
    Replies: 6
    Last Post: 10-25-2007, 09:46 AM
  2. approx. # CPU cycles
    By MadCow257 in forum C++ Programming
    Replies: 8
    Last Post: 01-05-2005, 04:39 PM