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;
middle=(low+high)/2;
if(low+1==high)
cout<<caculatePI(high)<<endl;
else
{
if(fabs((double)4.0/(2*middle-1))<err)
search_err(err,low,middle);
else
原文请找腾讯752018766辣,文-论'文.网http://www.751com.cn院
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);