//已知一个误差,求π的近似值
//π=4*(1-1/3+1/5-1/7+...)
#include<stdio.h>
double CircleRatio(double x);
int main()
{
double x;
printf("请输入一个误差值:\n");
scanf("%Lf",&x);
x = CircleRatio(x);
printf("π的近似值为:%Lf",x);
return 0;
}
double CircleRatio(double x)
{
int sign = 1; //表示符合,第一项是正数
int i = 1; //表示第一项
double abs; //表示某一项的绝对值
double term; //表示某一项
double accum = 0;//存储累加和
while(1)
{
term = sign*1.0/(2*i-1);
accum += term;
abs = term>0?term:-term;
if(abs<x) //x表示已知的误差值,若某一项的绝对值小于该误差了,则累加结束
break;
i++;
sign = -sign;
}
return 4*accum;
}
11-04
1万+
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
05-24