The Euler’s number e is a mathematical constant approximated at 2.718. The formu
ID: 3757705 • Letter: T
Question
The Euler’s number e is a mathematical constant approximated at 2.718. The formula for computing it is as follows:
e = 1 + 1/1! + 1/2! + 1/3! + 1/4! + ...
where n! = n×(n-1)×(n-2)×...×1, e.g., 4!=4×3×2×1
Write a program in C named euler.c that approximates the value of e by using the following equation:
e = 1 + 1/1! + 1/2! + 1/3! + 1/4! + ... + 1/n! where n is a number entered by the user.
Your program will first compute e as 1, then as 1 + 1/1!, then as 1 + 1/1! + 1/2! and so on. In each step, print the step number and the value of e, as follows:
1: 2.000000
2: 2.500000
3: 2.666666
... ...
Hint:
(1) First ask the user for an input integer n (n should be no less than 1);
(2) Your program should consist of two for loops: The first loop should have a counting variable i that counts from 1 to n. Each value of i corresponds to one step as we just mentioned above. The second loop, which should be inside the body of the first loop, computes i! for a given i. For example,
int product = 1;
for(int j = i; j > 0; j--){
product *= j; }
Explanation / Answer
#include <stdio.h>
double eCalc(int terms, double e);
int main()
{
int dummy;
int terms;
double e;
do
{
printf("Enter number of terms: ");
scanf_s("%d", &terms);
} while (terms <= 0);
while ((eCalc(terms, e) - eCalc(terms - 1, e)) < 0.0000001)
{
printf("An approximation of Euler's number is: %e", e);
}
printf(" The program has finished. Press enter to exit. ");
scanf_s("%d", &dummy);
return 0;
}
double eCalc(int terms)
{
if (terms == 1)
return = 0;
else
return = 1 / (terms*(terms - 1));
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.