Need help understanding Math in C++ -
hey guys doing credit program , run every input use ends 1. can point me right direction on messed please , 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 negative"); printf("enter value of n: "); scanf_s("%d", &n); } printf("n! stirling approximation value %i %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)); } }
you 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 missed out important part of the formula, floating point division above expression still not return correct value.
look @ series again:
in order evaluate you're going need (a) use floating point throughout , (b) you'll need include sqrt(2 * pi * n) * pow(n / e, n)
term too. can omit first few terms of series, though, depending on required accuracy (apparently assignment requires use first 4 terms).
Comments
Post a Comment