> 其他 >
使用C++,求pi的近似值
用下面的公式求pi的近似值
pi/4 = 1-1/3+1/5-1/7+.
直到最后一项的绝对值小于10的-7次方为止
如下式我自己编的
#include "stdafx.h"
#include "iostream"
#include "cmath"
#include "conio.h"
using namespace std;
int _tmain(int argc,_TCHAR* argv[])
{
int n = 1;
double P = 0,pi;
for(n=1;1/(2*n-1) > 10^(-7);++n)
{
P += ((-1)^(n+1))*(1/(2*n-1));
}
pi = P*4;
cout
人气:263 ℃ 时间:2020-02-03 04:56:12
解答
注意:1/2的结果为0!1.0/2的结果为0.5
所以应该如下修改
int t=1;
for(n=1;1.0/(2*n-1) > 1e-7;++n)
{
P += t*(1.0/(2*n-1));
t=-t;
}贴出来完整的代码好吗,我拿着你给的东西去改仍然 出问题而且有关1,-1的那个东西,为什么不可以用(-1)^(2n-1)这样子去判断呢
推荐
猜你喜欢
© 2024 79432.Com All Rights Reserved.
电脑版|手机版