Print Friendly and PDF
(Factorial) The factorial of a nonnegative integer n is written n! (pronounced “n factorial”) and is defined as follows: n! = n · (n – 1 ) · (n – 2) · … · 1 (for values of n greater than 1 ) and n! = 1 (for n = 0 or n = 1 )
(Factorial) The factorial of a nonnegative integer n is written n! (pronounced “n factorial”)
and is defined as follows:


n! = n · (n – 1 ) · (n – 2) · … · 1 (for values of n greater than 1 )
and
n! = 1 (for n = 0 or n = 1 )

For example, 5! = 5 · 4 · 3 · 2 · 1 , which is 1 20. Use while statements in each of the following:

a) Write a program that reads a nonnegative integer and computes and prints its factorial.
b) Write a program that estimates the value of the mathematical constant e by using the
formula:

e = 1 + 1 /1 ! + 1 /2! + 1 /3! + ...
Prompt the user for the desired accuracy of e (i.e., the number of terms in the summation).
c) Write a program that computes the value of ex by using the formula
ex = 1 + x/1 ! + x2/2! + x3/3! + ...
Prompt the user for the desired accuracy of e (i.e., the number of terms in the summation).

Solution:

a)

int n;
int y;

int result = 1;
cout << "Enter number: ";
cin >> n;
while( n > 0 ) {
result = result * n;
n‐‐;
}
cout << result << endl;
b)
int n;
int inn;
double e = 0;
int x;
double result;
cout << "Enter number: ";
cin >> n;
x = n;
while( n > 0

{
inn = n;
result = 1;
while( inn > 0

{
cout << "1. result and inn " << result << " " << inn << endl;
result = result * inn;
inn‐‐;
cout << "2. result and inn " << result << " " << inn << endl;
}
cout << "1. e and x " << e << " " << x << endl;
e += (1 / result) ;
n‐‐;
x‐‐;
cout << "2. e and x " << e << " " << x << endl;

}

cout << setprecision(30) << (e + 1) << endl;
c)
int n;
int number;
double fact;
double e = 1;
int x, a;
int z = 1;
cout << "enter number: " << endl;
cin >> number;
x = number;
//factortial
while(z <= number

{
n = 1;
fact = 1;
a = number;

while( n <= number
{
fact *= n;
n++;
e += ( x / fact ) ;
x *= a;
z++;
}
}

cout << "e equal to " << static_cast( e ) << endl;

}
zubairsaif

Zubair saif

A passionate writer who loves to write on new technology and programming

Post A Comment:

1 comments:

  1. Hi, Great post!! Could you please explain your solution for c) please.

    ReplyDelete