在C++中计算n位圆周率的算法?

xuo3flqw  于 2022-11-19  发布在  其他
关注(0)|答案(1)|浏览(289)

这是我的资料

#include <iostream>
#include <iomanip>

using namespace std;

int main()
{
    double pi = 0;
    long i;
    long n;
    
    cout << "Enter the value of n: ";
    cin >> n;
    cout << endl;
    
    for (i = 0; i < n; i++)
    {
      if (i % 2 == 0)
          pi = pi + (1 / (2 * i + 1));
      else
          pi = pi - (1 / (2 * i + 1));
        pi = 4 * pi;
    }
    
    cout << endl << "pi = " << pi << endl;
    return 0;
}

然而,这并没有给予所需的输出。例如,n = 9,pi = 262144。我知道可以将pi存储为常量并以这种方式得到结果,但我想知道使用上面的算法做错了什么。

baubqpgj

baubqpgj1#

因为long i;,对于任何i>0都是零,当i=0,对于i=1,9,你得到pi=1;,你得到pi = 4*pi;,这就是为什么你得到262144,也就是4^8
你可能需要

for (i = 0; i < n; i++)
{
  if (i % 2 == 0)
      pi = pi + (1.0 / (2 * i + 1));
  else
      pi = pi - (1.0 / (2 * i + 1));
}
pi = 4 * pi;

相关问题