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

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

这是我的资料

  1. #include <iostream>
  2. #include <iomanip>
  3. using namespace std;
  4. int main()
  5. {
  6. double pi = 0;
  7. long i;
  8. long n;
  9. cout << "Enter the value of n: ";
  10. cin >> n;
  11. cout << endl;
  12. for (i = 0; i < n; i++)
  13. {
  14. if (i % 2 == 0)
  15. pi = pi + (1 / (2 * i + 1));
  16. else
  17. pi = pi - (1 / (2 * i + 1));
  18. pi = 4 * pi;
  19. }
  20. cout << endl << "pi = " << pi << endl;
  21. return 0;
  22. }

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

baubqpgj

baubqpgj1#

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

  1. for (i = 0; i < n; i++)
  2. {
  3. if (i % 2 == 0)
  4. pi = pi + (1.0 / (2 * i + 1));
  5. else
  6. pi = pi - (1.0 / (2 * i + 1));
  7. }
  8. pi = 4 * pi;

相关问题