为什么 ,,伤不起啊
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int s=-1;
int n=1;
double u=0.0;
double pi;
while(fabs(u)>=1.0e-4)
{
s=-s;
u=u+(s/(2*n-1));
n++;
}
pi=4*u;
cout<<"pi="<<pi<<endl;
return 0;
}这个程序怎么就不能运行 怎么算不出正确的pi的值
[解决办法]
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int s=-1;
int n=1;
double u=0.0;
double pi;
while(fabs(1.0*s/(2*n-1)) >= 1e-4)//你原来的判断条件条件第一步就不成立了。。
{
s=-s;
u=u+(1.0*s/(2*n-1));//这里改一下。。否则结果永远为0。。
n++;
}
pi=4*u;
cout<<"pi="<<pi<<endl;
return 0;
}
#include <iostream>
#include <cmath>
using namespace std;
int main(void)
{
int s = -1;
int n = 1;
double u = 0.0, tmp = 0.0;
double pi;
do
{
s = -s;
tmp = s * 1.0 / ( 2*n - 1); //注意这儿需要乘1.0,原因是你懂得
u = u + tmp;
n++;
} while(fabs(tmp) >= 1.0e-6); //建议精确到小数点后6位,这样更精确~
pi = 4 * u;
cout<<"pi = "<<pi<<endl;
return 0;
}