利用公式求π的近似值,数列取前1,000,000项,输出结果保留小数点后八位。(求一个完整编程,容易犯的错误)
采用莱布尼茨无穷级数求PI,PI/4 = 1- (1/3) + (1/5) - (1/7) + ...
#include <stdio.h>
/* PI/4 = 1- (1/3) + (1/5) - (1/7) + ...*/
int main()
{
unsigned int max = 1000000; // 最大迭代次数
int count = 0; // 迭代计数
double pi = 0;
unsigned k = 1; // 数列项分母
int sign = 1; // 控制正负号
while (count < max)
{
pi += sign * (1.0 / k);
k += 2;
sign = -sign;
count++;
}
pi *= 4;
printf("%.8lf", pi);
return 0;
}
#include<stdio.h>
#include<math.h>
double fm(double a)
{
return 2*a-1;
} //定义分母函数
int h(int a)
{
if(a%2==0) return -1;
else return 1;
} //定义正负函数
int main()
{
double a,sum=0,p;
for(a=1;fabs(h(a)/fm(a))>=1e-6;a++)
{
sum+=h(a)/fm(a);
}
p=4*sum;
printf("PI:%.8lf",p);
return 0;
}