使用莱布尼兹公式的C ++ Pi逼近 [英] C++ Pi Approximation using Leibniz Formula
问题描述
我是C ++的初学者,并且自己编写代码,因此请原谅任何词汇上的不幸.我找不到这个特定的问题,但是在互联网上找不到类似的问题,但是我仍然很难获得我需要的结果.
I'm a beginner at C++ and coding itself, so please forgive any vocabulary mishaps. I couldn't find this specific question but similar ones on the internet, but I'm still having a hard time getting an outcome I need.
因此,我正在使用Leibniz公式来估算pi,即
So I'm using the Leibniz Formula to approximate pi which is:
pi = 4·[1 – 1/3 + 1/5 – 1/7 + 1/9…+(–1 ^ n)/(2n +1)].
pi = 4 · [ 1 – 1/3 + 1/5 – 1/7 + 1/9 … + (–1 ^ n)/(2n + 1) ].
我编写了一个可编译且可运行的程序,但令我困扰的代码的主要部分是:
I've written a compilable and runnable program , but the main part of the code that's troubling me is:
if (terms > 0){
double partial = 0;
for (i = 0; i < terms; i++)
if (i % 2 == 0)
partial -= (pow(-1,terms))/((2.0 * i) + 1);
else
partial += (pow(-1,terms))/((2.0 * i) + 1);
double newPi = 4 * partial;
cout << "The approximation is " << newPi << " using " << terms << " terms.\n";
}
如果项= 3,则近似值= 2.895
If terms = 3, the approximation = 2.895
如果项= 10,则近似值= 3.232
If terms = 10, the approximation = 3.232
如果项= 50,则近似值为3.161
If terms = 50, the approximation = 3.161
我没有这些号码.但是我注意到,当我输入奇数时,我得到一个负数,反之亦然.我在程序中编写的所有内容都是到目前为止我在课堂上学习的所有内容,因此我无法真正超出我编写的范围.任何帮助或解释将不胜感激.
I'm not getting any of these numbers. I've noticed though, that when I put in an odd number, I get a negative and vice versa with even numbers. Everything I have written in my program is everything I have learned in my class so far, so I cannot really go out of the scope I've written in. Any help or explanation would be appreciated.
推荐答案
您可以通过if/else来确定符号,但是您也可以执行pow(-1, terms)
.我将摆脱pow
并将其替换为1
,因为您已经在执行partial +=
和partial -=
了,这取决于i
是奇数还是偶数.另外,我认为您的+=
和-=
应该相反.
You have an if/else to determine the sign, but then you also do pow(-1, terms)
. I would just get rid of the pow
and replace it with 1
, since you are already doing partial +=
and partial -=
depending if i
is odd or even. Also, I think your +=
and -=
should be the other way around.
这篇关于使用莱布尼兹公式的C ++ Pi逼近的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!