Search code examples
ceulers-number

What's wrong with my code: wrong value output when I try to calculate Euler's number, e, in C?


I'm trying to approximate Euler's number in C using a loop that terminates when the difference between two successive values of e is less than 0.0000001. The value I get is 2.99.. I tried setting it up so that with each iteration, e will be compared with the previous value of itself (held in e1) and if the difference is greater than 0.0000001 it will add another term 1/(n!). What's the issue? I'm new to programming so any advice/critiquing is appreciated.

#include <stdio.h>
int main()
{
    float e1 = 0, e2 = 1;
    int n = 1, nfact; 

    while ((e2 - e1) > 0.0000001)         
    {
        e1 = e2;   
        nfact = 1;
        for (int count = 1; count < n; count++)     
        {
            nfact = n * count;
        }
        n = n + 1;
        e2 = e1 + (1.0 / nfact);
    }   

    printf("Approximated value of e = %f", e2);
    return 0;
}

Solution

  • nfact = 1;
    for (int count = 1; count < n; count++)     
    {
        nfact = n * count;
    }
    

    won´t calculate n!.
    nfact gets a completely new value every iteration. Surely you mean

    nfact = 1;
    for (int count = 2; count <= n; count++)     
    {
        nfact *= count;
    }