用C++计算圆周率;我哪里搞砸了?

Calculating Pi with C++; Where am I messing up?

为了好玩,我正在尝试使用众所周知的算法来计算圆周率: pi/4 = 1 - (1/3) + (1/5) - (1/7) + (1/9),等等.... 然后将所得结果乘以 4 得到 pi(近似值)。 在过去的 45 分钟左右的时间里,我一直在编写并尝试让这段代码正常工作。我哪里搞砸了?任何帮助将不胜感激。

//I'm new, which of these are necessary in this program?
#include <iostream>
using namespace std;
#include <string>
#include <math.h>

int main()
{
//1.0 as 1/4 pi is used as part of the algorithm in the for loop
float pi_fourth = 1.0;
//to be used as a counter inside for loop
int i = 5;
//I want the for loop to stop after only a few iterations
for (pi_fourth = 1.000000; i < 20 ; i + 4)
{
    //algorithm for determining one-fourth pi
    // algorithm is pi/4 = 1 - 1/3 + 1/5 - 1/7 + 1/9, etc...
    (pi_fourth -= 1/i) += (1/(i-2));
}
//now to complete the program, I need to multiply result
//  of the for loop to get pi approx.
float real_pi = (pi_fourth * 4);
//final print statement to reveal pi to a few digits
cout << "pi is ABOUT " << endl << real_pi << endl;
return 0;
}

当它运行时,没有错误出现,它只是永远不会到达最终的打印语句,这让我相信这是一个无限循环。这是一个正确的假设吗?如果答案非常简单,我深表歉意;正如我之前提到的,我是 C++ 的新手。

for (pi_fourth = 1.000000; i < 20 ; i + 4)

i 它没有递增。尝试

for (pi_fourth = 1.000000; i < 20 ; i += 4)

我做了一个固定版本的程序,有评论:

#include <iostream>
// Only iostream is needed for cout and endl.
// using namespace std is usually not recommended on global scope

int main()
{
    float pi_fourth = 1.0;
    int i = 3;
    for(; i < 1000; i += 4)
    {
        // pi_fourth was already initialized. using 1.00000 instead of 1.0 has no effect.
        // i += 4 to add to i
        // fixed the algorithm, and wrote it in two statements.
        // 1.0/i instead of 1/i, otherwise it would be an integer division (because both 1 and i are integers).
        pi_fourth -= 1.0/i;
        pi_fourth += 1.0/(i + 2);
    }
    float real_pi = pi_fourth * 4.0;
    std::cout << "pi is ABOUT " << std::endl << real_pi << std::endl;
    return 0;
}

这里有一些想法,与代码中的错误关系不大

在变号系列中,错误不超过最后一个删除项。因此,典型的方法是询问用户所需的精度,并根据该精度计算要求和的项数,表示为 N.

应该从最小项开始向最大项求和,这样可以使舍入误差较小并受到控制。所以循环看起来像

for(int i = N; i > 0; i -= 2)

最好每一个循环周期添加一项,沿着线的某处

double sign = 1.0;
double pi = 0.0;
for(int i = N; i > 0; i -= 2) {
    auto term = sign / double(i);
    pi += term;
    sign = -sign;
}

return fabs(pi); // might be negative value