1156:求π的值
【题目描述】
【输入】
(无)
【输出】
ππ的值。保留到小数点后10位。
【输入样例】
(无)
【输出样例】
(无)
知识补充:
浮点类型
float 至少精确6位有效数字
double 至少精确13位有效数字
cmath函数:
pow();几次幂。
sqrt(); 开根号。
代码块:
//1156:求π的值
#include<iostream>
#include<cmath>
#include<iomanip>
using namespace std;
double arctanx(double x);
int main()
{
double pi=0;
pi=6.0*arctanx(1.0/(sqrt(3)));
cout<<fixed<<setprecision(10)<<pi;
return 0;
}
double arctanx(double x)
{
double value=0;
int i=1,index=1;
while(1)
{
value=value+(index*((pow(x,i))/i));
i=i+2;
if(((pow(x,i))/i)<=pow(10,-6))
{
return value;
}
index=-index;
}
}
问题反思:
一开始始终编译不过,答案是3.1415905109。
找到网上的答案,进行到19结束,我的是21结束,所有讲if判断放在了最后,结果答案出来,所以这个地方确实不是很理解。
别人的答案:
#include<iostream>
#include<cstdio>
#include<cmath>
using namespace std;
double cal(double x);
int main()
{
double a,pi;
a = 1/sqrt(3);
pi = 6 * (cal(a));
printf("%.10lf\n",pi);
return 0;
}
double cal(double x)
{
double sum = 0,tmp = x;
int i = 1;
while(fabs(tmp / i) >= 1e-6)//x−x^3/3+x ^ 5
{
sum += tmp / i; //和累加
tmp=-1 * x * x * tmp; //分子 x 连乘 正负号错位
i += 2;//分母相差2 的奇数
}
return sum;
}