【发布时间】:2017-10-10 20:29:02
【问题描述】:
所以我不知道为什么我的代码不起作用,基本上我正在编写的函数使用泰勒级数计算 Pi 的估计值,每当我尝试运行程序时它就会崩溃。
这是我的代码
#include <iostream>
#include <math.h>
#include <stdlib.h>
using namespace std;
double get_pi(double accuracy)
{
double estimate_of_pi, latest_term, estimated_error;
int sign = -1;
int n;
estimate_of_pi = 0;
n = 0;
do
{
sign = -sign;
estimated_error = 4 * abs(1.0 / (2*n + 1.0)); //equation for error
latest_term = 4 * (1.0 *(2.0 * n + 1.0)); //calculation for latest term in series
estimate_of_pi = estimate_of_pi + latest_term; //adding latest term to estimate of pi
n = n + 1; //changing value of n for next run of the loop
}
while(abs(latest_term)< estimated_error);
return get_pi(accuracy);
}
int main()
{
cout << get_pi(100);
}
代码背后的逻辑如下:
- 定义所有变量
- 将 pi 的估计值设置为 0
- 计算泰勒级数中的一项并计算误差 这个词
- 然后它将最新项添加到 pi 的估计中
- 然后程序应计算出系列中的下一项和其中的误差,并将其添加到 pi 的估计值中,直到满足 while 语句中的条件
感谢您的帮助
【问题讨论】:
标签: c++ loops do-while pi taylor-series