Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I am having trouble on how to tackle this. I see that Stirling\'s formula must b

ID: 3931871 • Letter: I

Question

I am having trouble on how to tackle this.

I see that Stirling's formula must be solved and it must be outside the loop for calculating n!

#include "stdafx.h"
#include <iostream>
#include <math.h>
using namespace std;


int main()
{
double answer, input, approximation;
double e, pi;
e = 2.71828182845904523536;
pi = 3.14159265;
input = 20;
answer = 1;

// cout << "If your input was ... " << input << endl;
approximation = sqrt(2 * pi*input)*pow((input / e), input);
cout << "Your approximation equals ... " << approximation << endl;

do
{

answer = answer * input;
input = input - 1;

} while (input >= 1);

cout << "N! equals ... " << answer << endl;


system("pause");
return 0;
}

Explanation / Answer

The code is running fine for me. I am not sure what problem you are facing. If it is about how to do that for multiple values, I have provided the code below.

One suggestion though: Instead of writing values of e and pi yourself, you can use the math library from cpp.

So, e = exp(1.0);

pi = acos(-1.0);

It just makes the code more abstracted in my opinion.

Also, use functions instead to make code more abstracted.

stirling.cpp

#include "stdafx.h"
#include <iostream>
#include <math.h>
using namespace std;

double stirling(int n, double e, double pi);

double factorial(int n);

int main()
{
    double answer, input, approximation;
    double e, pi;
    e = 2.71828182845904523536; //or use e = exp(1.0)
    pi = 3.14159265; //or use pi = acos(-1.0)
    int n = 20;

    for (int i=1; i<n; i++){
        cout << "Your approximation equals ... " <<stirling(i, e, pi) << endl;
        cout << "N! equals ... " <<factorial(i)<< endl;
    }

    return 0;
}

double stirling(int n, double e, double pi){
    return sqrt(2*pi*n)*pow((n/e), n);
}

double factorial(int n){
    if (n==1){
        return 1.0;
    }
    else{
        return n * factorial(n-1);
    }
}