C ++ Chudnovsky Pi的公式 [英] C++ Chudnovsky Formula for Pi
本文介绍了C ++ Chudnovsky Pi的公式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想让一个C ++应用程序为我计算pi。
这里是我的代码:
我已经尝试执行Chudnovsky公式, #include< iostream>
#include< cmath>
long fac(long num){
if(num == 1)
return 1;
return fac(num - 1)* num;
}
int main(){
using namespace std;
double pi;对于(long k = 0; k <10; k ++){
pi + =(pow(-1,k)* fac(6 * k)*(13591409 +(545140134 * k) )/(fac(3 * k)* pow(fac(k),3)* pow(640320,3 * k + 3/2)
}
pi * = 12;
cout<< 1 / pi < endl;
system(pause);
return 0;
}
这样做的目的是让程序输出10次Chudnovsky公式。相反,我得到这个:
调用重载的pow(int,long int&)'是不明确的
解决方案
您从不初始化 pi
fac(0)
应为 1
)。 $ b
3/2
计算为 1
(因为它使用整数除法, ),这使得你的公式评估为完全错误的答案。
I am trying to make a C++ application calculate pi for me. I have tried to implement the Chudnovsky formula with no luck.
Here is my code:
#include <iostream>
#include <cmath>
long fac(long num) {
if (num == 1)
return 1;
return fac(num - 1) * num;
}
int main() {
using namespace std;
double pi;
for (long k = 0; k < 10; k++) {
pi += (pow(-1, k) * fac(6 * k) * (13591409 + (545140134 * k))) / (fac(3 * k) * pow(fac(k), 3) * pow(640320, 3 * k + 3/2));
}
pi *= 12;
cout << 1 / pi << endl;
system("pause");
return 0;
}
The goal of this was to have the program output 10 iterations of the Chudnovsky formula. Instead, I got this:
call of overloaded `pow(int, long int&)' is ambiguous
解决方案
You never initialize pi
, so your code has undefined behaviour.
Your fac
function does not correctly handle 0
(fac(0)
should be 1
).
3/2
evaluates to 1
(because it uses integer division, which truncates), and this makes your formula evaluate to the completely wrong answer.
这篇关于C ++ Chudnovsky Pi的公式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文