问答题
给定程序MODI1.C中函数fun的功能是:根据以下公式求π值,并作为函数值返回。
例如,给指定精度的变量eps输入0.0005时,应当输出Pi=3.140578。
π 1 1 2 1 2 3 1 2 3 4
─=1+ ─ + ─×─ + ─×─×─ + ─×─×─×─+……
2 3 3 5 3 5 7 3 5 7 9
请改正程序中的错误,使它能得出正确结果。
注意:不要改动main函数,不得增行或删行,也不得更改程序的结构。
给定源程序:
#include
#include
double fun(double eps)
{ double s,t; int n=1;
s=0.0;
/************found************/
t=0;
while( t>eps)
{ s+=t;
t=t * n/(2*n+1);
n++;
}
/************found************/
return(s);
}
main()
{ double x;
printf("/nPlease enter a precision: "); scanf("%lf",&x);
printf("/neps=%lf, Pi=%lf/n/n",x,fun(x));
}
【正确答案】第一处: 初始化t的值,根据程序中的计算程序和试题的要求得出,t应为1。
第二处: 根据公式π/2得出,所以返回时应原有s的基础上乘以2作为返回值。
【答案解析】