[英]Need help understanding Math in C++
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 大家好,我正在执行一个额外的学分程序,但是我可以运行它,但是我使用它的每次输入总是以1结尾。有人能指出我正确的方向吗,谢谢。
#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));
}
}
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. 为了对此进行评估,您将需要(a)始终使用浮点,并且(b)您还需要包括
sqrt(2 * pi * n) * pow(n / e, n)
项。 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). 但是,根据所需的精度,您可以忽略除系列的前几个术语之外的所有其他术语(显然,您的作业仅要求您使用前四个术语)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.