这段代码通过傅里叶展开式计算圆周率
具体公式为:π=∑(-1)^n/(2n-1)
#include <iostream>
#include <math.h>
using namespace std;
int main(){
long double pi = 0;
long double n = 1, x = 1;
int sign = 1;
while ( fabs(x) > 1e-8){
pi = pi + 4*x;
n++;
sign = sign * (-1);
x = sign / double(2*n-1);
}
cout << "the value of pi is : " << pi << "\n" << endl;
return 0;
}
测试结果为:
the value of pi is : 3.14159
