For example, 5! = 5 · 4 · 3 · 2 · 1, which is 120. Use while statements in each of the following:
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).
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:
Prompt the user for the desired accuracy of e (i.e., the number of terms in the summation).
a) ```
// Compute and print the factorial of the specified value.
#include
using namespace std;
int main()
{
int number; // user input
int factorial = 1; // factorial of input value
// get input
cout << "Enter a positive Integer: ";
cin >> number;
cout << number << "! is ";
while ( number > 0 ) // calculate factorial
{
factorial *= number;
number--;
} // end while
cout << factorial << endl;
} // end main
```
Enter a positive Integer: 5
5! is 120
b) ```
// Estimate the value of e to the specified accuracy.
#include
using namespace std;
int main()
{
int number = 1; // counter
int accuracy; // accuracy of estimate
int factorial = 1; // value of factorial
double e = 1.0; // estimate value of e
// get accuracy
cout << "Enter desired accuracy of e: ";
cin >> accuracy;
// calculate estimation
while ( number < accuracy )
{
factorial *= number;
e += 1.0 / factorial;
number++;
} // end while
cout << "e is " << e << endl;
} // end main
```
You might also like to view...
When the audio icon is selected, options to control the volume, when the audio starts, and the duration of the audio are located on the ________ tab
A) Playback B) Transition C) Animation D) Format
A delimited text file is one in which the columns are separated by a character such as a tab or comma
Indicate whether the statement is true or false.