In: Computer Science
Use a while(true) loop to ask the user to “Enter a non-negative
integer (enter negative integer to
quit):”
and store this into an int named n.
If the user enters a negative int for n, the while loop is broken
via the brake statement. Otherwise,
in the remaining part of the while loop, use a for loop to compute
the sum of the inverse factorials
from 0 to n, that is sum = 1/0! + 1/1! + 1/2! + . . . + 1/n!
Use the iomanip library in order to print the sum with 50 decimal
digits of precision.
Sample output:
Enter a non-negative integer (enter negative integer to quit):
8
1/0! + 1/1! + 1/2! + 1/3! + 1/4! + 1/5! + 1/6! + 1/7! + 1/8! =
2.7182787698412700372330164100276306271553039550781
Enter a non-negative integer (enter negative integer to quit):
0
1/0! = 1
Enter a non-negative integer (enter negative integer to quit):
-3
Will like if correct thank you
c++
I have uploaded the Images of the code, Typed code and Output of the Code. I have provided explanation using comments (read them for better understanding).
Images of the Code:
Note: If the below code is missing indentation please refer
code Images
Typed Code:
// include required header
#include <iostream>
// including iomanip header
#include <iomanip>
// using std
using namespace std;
// A function named factorial to calculate factorial
// with input parameter x
int factorial(int x)
{
// If x is 0
if(x==0)
{
// returning 1
return 1;
}
else // otherwise
{
// calling factorial recursively
return x*factorial(x-1);
}
}
int main()
{
// A int variable named n to store user input
int n;
// a while true loop
while(true)
{
// Prompt for User input
cout << "Enter a non-negative integer (enter negative integer
to quit): ";
// reading value into n
cin >> n;
// if n is negative (less than 0)
if(n<0)
{
// breaking the while loop
break;
}
else // otherwise
{
// A variable to store sum of the inverse factorials
double sum = 0;
// for loop to compute the sum of the inverse factorials
for (int i = 0; i <= n; i++)
{
// calling function factorial with parameter as i
// adding the returned value to sum
sum = sum + (1/double(factorial(i)));
}
// a for to print the factorial expression
for (int i = 0; i < n; i++)
{
// print each term
cout << "1/" << i << "! + ";
}
// printing last term and equal's to symbol
cout << "1/" << n << "! = ";
// using iomanip method set precision to 50 decimal
//printing the sum
cout <<setprecision(50) << sum << '\n';
}
}
}
//code ended here
Output:
If You Have Any Doubts. Please Ask Using Comments.
Have A Great Day!