【问题标题】:Calculating Pi using the Taylor series C++使用泰勒级数 C++ 计算 Pi
【发布时间】:2017-09-27 21:01:22
【问题描述】:

我正在尝试实现一个函数来使用泰勒级数计算 pi,这是我的代码

#include <iostream>
#include <math.h>
using namespace std;

double pi(int n)
{
double sum = 1.0;
int sign = -1;

for (int i = 1; i < n; i++)
{
    sum += sign / (2.0 * i + 1.0);
    sign = -sign;
}
return 4.0 * sum;
}


int main()
{
 cout << "the value for pi is" << pi ;
}

由于某种原因,我的代码一直返回 1,但我不明白为什么

作为旁注,如果系列的最新项的绝对值小于 pi 的最新估计值中的误差,则执行 taylor 系列的代码将停止运行

我正在考虑通过使用类似的 for 循环来计算错误,并在整个函数中使用 do...while 循环,一旦满足此条件,就会停止计算 pi,但我不确定如果有更简单的方法可以做到这一点或从哪里开始。

我是这个论坛和 c++ 的新手,非常感谢我能得到的任何帮助

【问题讨论】:

  • cout &lt;&lt; "the value for pi is" &lt;&lt; pi; -> cout &lt;&lt; "the value for pi is" &lt;&lt; pi(1000);

标签: c++ function loops pi taylor-series


【解决方案1】:

你应该用某个值来评估函数,例如 10:

cout << "the value for pi is " << pi(2000)<<endl;

输出:

the value for pi is 3.14109

【讨论】:

    【解决方案2】:

    pi 在您的示例中是一个带有参数的函数。因此,您必须添加括号和类似 pi(50) 的参数。 50 只是一个示例,随心所欲。

    【讨论】:

      猜你喜欢
      • 2015-05-15
      • 2017-10-10
      • 1970-01-01
      • 2017-03-20
      • 2020-03-01
      • 1970-01-01
      • 2016-04-26
      • 1970-01-01
      • 2015-11-23
      相关资源
      最近更新 更多