0

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;
}
C.A.T.
  • 5
  • 1

3 Answers3

1

This is not how you calculate the factorial of a number:

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

Notice that you always assign to nfact on each iteration to the value of n*count, obliterating the previous value of nfact. This piece of code is equivalent to:

nfact = n*(n-1);

Since that's the last value of count.

I think you wanted this instead:

nfact = n;
for (int count = n-1; count > 0; count--)     
{
    nfact = nfact * count;
}
Filipe Gonçalves
  • 20,783
  • 6
  • 53
  • 70
1
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;
}
deviantfan
  • 11,268
  • 3
  • 32
  • 49
0

This is my code for estimates the value of the mathematical constant e by using the formula: e = 1 + 1/1! + 1/2! + 1/3! + ....

#include <stdio.h>

int main(void) {

    int n = 0;          /* loop counter for accuracy */
    int accuracy = 10;  /* current n factorial */
    int fact = 1;       /* degree of accuracy */
    double e = 0;       /* current estimated value of e */

/* loop until degree of accuracy */

    while (n <= accuracy) {

        if (n == 0) {
            fact *= 1;
        } else {
            fact *= n;
        }
        e += 1.0 / fact;

        ++n;

    }

    printf("e is %f", e);

    return 0;
}