注册 登录
编程论坛 C++教室

C++求Pi值问题

hurtdream 发布于 2008-08-02 16:38, 740 次点击
//==================================================
// pi.cpp
// 求Pi的方法
//==================================================
#include <iostream>
#include <cmath>
using namespace std;

int main()
{
    double sum=1, item=1;
    int denom=1, sign=1;
    while(abs(item)>1e-6)
    {
        denom += 2;
        sign *= -1;
        item = sign*1.0/denom;
        sum += item;
    }
    cout<<"Pi = "<<fixed<<sum*4<<endl;
    return 0;
}
//==================================================

这是书上的源码,运行的结果是Pi = 2.666667,大家帮忙看看是哪里的问题啊,就是按
Pi/4 = 1 - 1/3 + 1/5 - 1/7 + ...
这个公式来求的。
谢谢了
3 回复
#2
很远的那颗星2008-08-02 18:24
GCC编译,Code::Bolck里运行结果为3.141595
#3
blueboy820062008-08-02 18:45
while(fabs(item)>1e-6)

fabs() ...
#4
hurtdream2008-08-02 19:09
谢谢3楼的兄弟,可以了

回2楼,我用的是VC 6.0
1