#include <stdio.h>
#include <stdlib.h>
#include <math.h>
double get_Pi(double accuracy)
{
double Pi_estimate = 0;
double increment = 0;
double i = 0;
int s = -1;
while(fabs(increment) > accuracy)
{
increment = s*(1/(2*i+1));
Pi_estimate = Pi_estimate + increment;
s = -s;
i++;
}
double offset = 1.0;
Pi_estimate = Pi_estimate + offset;
return 4*Pi_estimate;
}
int main()
{
double accuracy;
printf("\nhow accurate do you want Pi? ");
scanf("%lf", &accuracy);
double approx = get_Pi(accuracy);
printf("%.10lf", approx);
return 0;
}
通过输入某个小数,您应该将 pi 变为 + 或 - 您输入的精度,但输出始终为 4.00000。
最佳答案
您从 0 而不是 1 开始,在项的分母中加法而不是减法,您正在使用整数运算而不是 float 计算 increment
的新值,并且您的while
循环永远不会进入,因为 increments
从 0 开始。
正确的公式是:pi/4 = sum(k->inf) ((-1)^(k+1))/(2k-1)
所以你会这样做:
double get_Pi(double accuracy)
{
double Pi_estimate = 0;
double increment;
double i = 1; // start at 1
int s = 1; // start with positive factor
do { // do the check at the bottom instead of the top
increment = s*(1.0/(2.0*i-1)); // use floating point constants to prevent integer division
Pi_estimate = Pi_estimate + increment;
s = -s;
i++;
} while(fabs(increment) > accuracy);
// no need to add an offset
return 4*Pi_estimate;
}
关于c - 无法从 C 中的近似公式获得正确的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54504935/