天天看点

关于π的近似值

#include

#includeusing namespace std;

int main()

{double an=1,sn=0.0,a=1.0;

int b=1;

while(abs(an)>=1e-8)

{sn+=an;

a+=2;

b=-b;

an=b/a;}

cout << “π的值是”<<4*sn<<endl;

return 0;}

[求π的近似值,π/4=1-1/3+1/5……]

1,c语言中求绝对值的函数为abs(),在C++中对函数abs()进行了重载,

这样方便了我们的使用,我们只要包含即可,例如:#include //C语言是math.h---------------------------------------------------------------我测试的例子代码如下:

#include #include//C语言是math.h

using namespace std;

void main(void)

2,while循环内部会存在循环语句按顺序输出的情况,所以自己按顺序走一遍防止出错。

关于π的近似值
![有问题顺序的代码](https://img-blog.csdnimg.cn/20201110235514470.jpg?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl81MjIwMTkwMg==,size_16,color_FFFFFF,t_70)
以下为正确顺序
#include<iostream>
#include<cmath>
using namespace std;

int main()
{double an=1,sn=0.0,a=1.0;
int b=1;
while(abs(an)>=1e-8)
{
sn+=an;

a+=2;
b=-b;
an=b/a;

}
 cout << "π的值是"<<4*sn<<endl;
 return 0;
}
           

继续阅读