Reputation: 3
Hey guys I am doing an extra credit program and I get it to run but every input i use it always ends up to be 1. Can anyone point me into the right direction on where i messed up please and thank you
#include<stdio.h>
#include<math.h>
#define Euler 2.718282
#define Pi 3.141593
int main(void)
{
int n;
int n_fact(int n);
printf("Enter n: ");
scanf_s("%d", &n);
while (n < 0)
{
printf("The n value must not be negative");
printf("Enter the value of n: ");
scanf_s("%d", &n);
}
printf("n! Stirling approximation value about %i is %i ", n, n_fact(n));
getchar();
getchar();
return 0;
}
int n_fact(int n)
{
if (n == 0)
{
return 0;
}
else
{
return (int)(1 + 1 / (12 * Euler) + 1 / (288 * n*n) - 139 / (51840 * n*n*n));
}
}
Upvotes: 0
Views: 65
Reputation: 213059
You are having problems here because of integer arithmetic, particularly integer division:
return (int)(1 + 1 / (12 * Euler) + 1 / (288 * n*n) - 139 / (51840 * n*n*n));
You have also missed out an important part of the formula, so even with floating point division the above expression will still not return the correct value.
Look at the series again:
In order to evaluate this you're going to need to (a) use floating point throughout and (b) you'll need to include the sqrt(2 * pi * n) * pow(n / e, n)
term too. You can omit all but the first few terms of the series, though, depending on required accuracy (apparently your assignment only requires that you use the first four terms).
Upvotes: 2