我正在尝试编写一个使用特定方程近似 pi 的程序。但是,当我运行代码时,它输出 4.8731472566 而不是 3.1415924576,我想知道我的代码中是否有任何错误。这是我到目前为止所拥有的
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n, i;
printf("n = ");
scanf("%d", &n);
double pi = 0.1;
double pi_1, pi_2, pi_3, pi_4, pi_5 = 0; //sets varibles that represent 4.0/((8*i)+1), etc. equal to zero
i = 0; // sets i equal to zero
while(i <= n){ // starts a loop with i is less than non-negative interger n
pi_1 = 4.0/((8*i)+1); //setting them equal to their respective parts of the equation
pi_2 = 2.0/((8*i)+4);
pi_3 = 1.0/((8*i)+5);
pi_4 = 1.0/((8*i)+6);
pi_5 = 1.0;
int j = 0; //creating new interger j
while(j <= i){ //as long as j isn't greater than i
pi_5 = pi_5*(1.0/16); //it will run the last part of the formula
j++;
}
pi += pi * (pi_1 - pi_2 - pi_3 - pi_4 - pi_5); //sets pi = to the entire formula
i++;
}
printf("PI = %.10f\n", pi);
return 0;
}
这是等式...
我尝试将 pi 更改为不同的整数,例如 0.001 和 1,但这不起作用
您的计算方式有一些错误
pi
。 pi
应该从 0.0
开始,并且 pi += pi * (pi_1 - pi_2 - pi_3 - pi_4 - pi_5);
不应该包含 pi *
部分,您应该乘以 pi_5
来代替,并且 while
循环条件应该是 j < i
。
我想出了这个函数(它利用
<math.h>
,而不是用循环计算功率)。我在这里使用 k
,因为它与我在公式函数中提供的链接中使用的相同。
double approximatePI(int steps) {
// https://en.wikipedia.org/wiki/Bailey–Borwein–Plouffe_formula
double pi = 0.0;
for (int k = 0; k < steps; ++k) {
const double multiplicand = 1.0 / pow(16.0, k);
const double minuend = 4.0 / (8.0 * k + 1.0);
// if you add all of them and subtract then together its
// the same result as if you subtract all of them individually
const double subtrahend = 2.0 / (8.0 * k + 4.0) +
1.0 / (8.0 * k + 5.0) +
1.0 / (8.0 * k + 6.0);
pi += multiplicand * (minuend - subtrahend);
}
return pi;
}
使其成为自己的功能,可以更轻松地在多个地方使用它。顺便说一句,如果您在 stackoverflow 上发布代码(或者您只是想自己调试它),如果您提供一些恒定值,例如
n
(或者我在函数中称之为 steps
),而不是使用 scanf()
在每次运行时从用户那里获取它。