请高人指点C语言问题

来源:百度知道 编辑:UC知道 时间:2024/06/04 02:49:13
编写程序:根据公式 ,输出 π的值。
要求:
(1)变量π为单精度类型,n为整型;
(2)计算当n的取值分别为20,50 ,100,200时的π值,说明什么问题?
(3)修改程序,不给出n值,而改为求π值,直到最后一项的数值小于10-4 为止。
(4)对修改后的程序,输出π值以及总的项数n。输出格式为:π=值;n=值。

#include<iostream>
#include<cmath>
using namespace std;
float fun(double i)
{
float PI=0;
for(double j=1;j<=i;j++)
{
PI+=4*float((1/(2*j-1))*pow(-1,j+1));

}
return PI;
}
void main()
{
float PI=0;
double i=1;

cout<<"n=20 "<<"π="<<fun(20)<<endl;
cout<<"n=50 "<<"π="<<fun(50)<<endl;
cout<<"n=100 "<<"π="<<fun(100)<<endl;
cout<<"n=200 "<<"π="<<fun(200)<<endl;
while(1/(2*i-1)>10e-4)
{
PI+=4*float((1/(2*i-1))*pow(-1,i+1));
i++;
}
cout<<"π="<<PI<<endl;
cout<<"n="<<i<<endl;
}