Use the for and while loops to calculate the value of e [e = 1 + 1/1! + 1/2! + 1/3! + 1/4! + 1/5! +... + 1/n!], While

/* Write a program and calculate the value of e according to the following formula. Two calculation methods are required: 1) for loop, calculation of the first 50 items 2) while loop until the value of the last item is less than 10-4e = 1 + 1/1! + 1/2! + 1/3! + 1/4! + 1/5! +... + 1/n! */# Include <stdio. h> // ============================================ ==========================/// use for to evaluate the value of e double () {double sum = 1, temp = 1; int I; for (I = 1; I <50; I ++) {temp/= I; sum + = temp ;} return sum ;} // ================================================ ====================/// use the while loop to evaluate the value of e double While () {double sum = 1; // The first item is set to 1 double temp = 1; int I = 1; while (temp> = 1e-4) {// [e = 1 + 1/1! + 1/2! + 1/3! + 1/4! + 1/5! +... + 1/n !] Temp = temp/I; // The second item is 1/1, that is, 1/1 !; Item 3: 1/2, that is, 1/2 !; Item 4 (1/2)/3, I .e. 1/3 !... Sum = sum + temp; I ++;} return sum; // return sum} // main function int main () {double a = (); double B = While (); printf ("Use the for loop to find the sum of the first 50 items of e is % lf \ n", ); printf ("using the while loop to obtain e and % lf \ n", B); return 0 ;}

Compile the program. e is equivalent to e ≈ 1 + 1/1 + 1/2! + 1/3! + 1/4! + · + 1/n! (1) Use the for loop to calculate the first 50 items (2) use the while LOOP

(1)

# Include <stdio. h>

Void main ()

{

Int n = 1;

Float I = 1, e = 1;

For (n = 1; n <= 50; n ++)

{

I = I * n;

E = e + 1/I;

}

Printf ("% f", e );

}

(2)

# Include <stdio. h>

Void main ()

{

Int n = 1;

Float I = 1, e = 1;

While (1/I> 10e-4)

{

I = I * n;

E = e + 1/I;

N ++;

}

Printf ("% f", e );

}

E = 1 + 1/1! + 1/2! + 1/3! + 1/4! + ...... 1. Use the for loop to calculate the first 50 items. 2. Use the while loop until the last item is less than 10-6 times.

A while statement loop error occurs. t really follows the 1/1 !, 1/2 !, 1/3! Is it changed like this? According to your definition, the first cycle t = 1 is correct, the second cycle, t ++ (t = 2), t * = t (t = 4 ), t = 1/t (t = 0.25), not equal to 1/2! (0.5. Its own algorithms are incorrect. At least one variable should be defined to indicate the denominator of each item.

For statement Loop Error. Neither the initial e value nor the t value equals 1/1 !, 1/2 !, 1/3! This changes.

Refer:

# Include <stdio. h>

# Include <math. h>

Int f (int n)

{

Long k = 1; int I;

For (I = 1; I <= n; I ++)

K = k * I;

Return k;

}

Main ()

{

Float e = 1, t;

Int m = 1;

While (fabs (t)> = 1e-6)

{

T = 1.0/f (m ++ );

E + = t;

}

Printf ("e = % f", e );

}