一、Π的计算公式
二、题目分解
题目可以分解为两个函数。分别为求幂次函数和求反正切函数。
三、实现步骤
1.函数声明
代码如下(示例):
#include <iostream>
using namespace std;
double power(double x, int num);
double arctan(double x);
double get_pai();
2.函数定义
代码如下(示例):
double power(double x, int num) {
double result = 1.0;
while (num--)
{
result *= x;
}
return result;
}
double arctan(double x) {
double result = 0;
int head = 1;
while (power(x, head)/ head>1e-15)
{
result = head % 4 == 1 ? result + power(x, head) / head: result - power(x, head) / head;
head += 2;
}
return result;
}
double get_pai() {
return 16 * arctan(1 / 5.0) - 4*arctan(1 / 239.0);
}
3.主函数
int main()
{
double pai= get_pai();
cout << pai << endl;
return 0;
}
注意事项
在C++中,整数/整数为整数!!!!!!!