改错题
1. 下列给定程序中,函数proc()的功能是:根据以下公式求π的值,并作为函数值返回。
例如,给指定精度的变量eps输入0.0001时,应当输出Pi=3.141358。
π/2=1+1/3+1/3*2/5+1/3*2/5*3/7+1/3*2/5*3/7*4/9…
请修改程序中的错误,使它能得出正确的结果。
注意:不要改动main()函数,不得增行或删行,也不得更改程序的结构。
试题程序:
#include<conio.h>
#include<stdio.h>
#include<math.h>
double proc(double eps)
{ double s,t;int n=1;
s=0.0:
t=1;
//****found****
while(t>eps)
{ s+=t;
t=t*n/(2*n+1);
n++;
//****found****
return(s);
}
void main()
{ double s;
printf("\nPlease enter a precision:"):
scanf("%1f",&s);
printf("\nPi=%1f\n",proc(s));
}
【正确答案】(1)错误:while(t>eps)
正确:while(t>=eps)
(2)错误:return(s);
正确:return(s*2);
【答案解析】 变量eps为给定的精度,当变量t等于精度值的时候还要继续进行运算,因此,“while(t>eps)”应改为“while(t>=eps)”。程序中求出的是π/2的值,而题目要求返回π的值,因此,“return(s)”应改为“return(s*2)”。