C++计算πPAI的近似值源代码
2.1需求分析
已知计算圆周率π有关的公式:
     π/4 = 1 - 1/3 + 1/5 -1/7 + 1/9 -…
(1)计算200项得到的近似π;
(2)要求误差小于0.000001的π的近似值。
运行结果截图
2.2  概要设计
函数caculatePI用于计算第n项PI的近似值
search_err用折半法在其上下界搜索
caculate_err通过每次n*2加速搜索区间
流程图:
函数caculatePI 
函数search_err
 函数caculate_err
 Main函数
 2.3  详细设计与编码
见上传程序。
2.4  调试分析
程序看似简单,但对各个函数的声明在编写过程中遇到很多错误,变量是声明等等。
根据错误提示还是可以调试出来的。
2.5  用户使用说明
根据界面提示,输入想要的数据。
  2.6  设计心得
  程序编写过程中遇到很多麻烦,尤其是变量的声明和函数的声明,并不是和自己想象的那样简单,同时程序的要点也在于此处。
#include<iostream>
#include<iomanip>
#include<cmath> 
using namespace std;
double caculatePI(int n)    //计算第n项PI的近似值
{
 double ret=0;
 while(n)
 {
  if(n%2)
   ret+=double(1)/(2*n-1);
  else
   ret+=(-1)*double(1)/(2*n-1);
  n--;
 }
 return 4*ret;
}
void search_err(double err,int low,int high)  //用折半法在其上下界搜索
{
 int middle;
原文请找腾讯752018766辣.文-论'文;网http://www.751com.cn   if(fabs((double)4.0/(2*middle-1))<err)
   search_err(err,low,middle);
  else
   search_err(err,middle,high);
 }
}
void caculate_err(double err)  //通过每次n*2加速搜索区间
{
 int n=2;
 int pre=1;
 while(1)
 {
  if(fabs(((double)4.0/(2*n-1)))<err)
   break;
  pre=n;
  n=2*n;
 }
 search_err(err,pre,n);void main()
{
 int n;
 cout<<"输入项数:"<<endl;
 cin>>n;
 cout<<"PI为:"<<setiosflags(ios::fixed)<<caculatePI(n)<<endl;
 cout<<"误差小于0.000001的π的近似值为"<<endl;
 caculate_err(0.000001);
 cout<<setiosflags(ios::scientific);1821