我正在编写一个程序,用一个特定的方程来近似计算π。然而,当我运行代码时,它输出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;
}
这是方程式
我试过把圆周率改变成不同的整数,比如0.001和1,但都不起作用
3条答案
按热度按时间whlutmcx1#
在计算
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
,因为它与我在函数中提供的公式链接中使用的相同。使其成为自己的功能,使其更容易在多个地点使用。顺便说一句,如果你在stackoverflow上发布代码(或者你只是想自己调试它),如果你提供一些常量值,例如,
n
(或者我在函数中称之为steps
),而不是每次运行时都使用scanf()
从用户那里获取它。svmlkihl2#
除了其他人的建议:
提示:与其使用开销较大的循环或缓慢的
1/pow(16,i)
调用来计算pi_5
,不如使用先前的值来快速形成新的值。1u4esq0p3#
回顾代码,似乎有很多不必要的变量和循环。我确实看到添加了一个答案,但我想我会继续添加我的简化版本,它也利用了math.h文件和数学库。
在重构后的代码中替换了一个简单的“for循环”,并使用求和公式,只需要“pi”变量。以下是一些示例输出。
唯一需要指出的是,当使用“math.h”包含文件时,需要在构建的链接部分进行引用,通常使用“-lm”,因为“m”是数学函数库。