为什么这调用函数里s1=s1*n/(2*n+1);变成 s1=s1*(n/(2*n+1));结果就变了?
题目
为什么这调用函数里s1=s1*n/(2*n+1);变成 s1=s1*(n/(2*n+1));结果就变了?
#include
#include
double fun ( double eps)
{
double s=1.0,s1=1.0;
int n=1;
while(s1>=eps)
{
s1=s1*n/(2*n+1);
s=s+s1;
n++;
}
return(2*s);
}
main( )
{ double x;void NONO ();
printf("Input eps:") ;
scanf("%lf",&x); printf("
eps = %lf,PI=%lf
",x,fun(x));
NONO();
}
void NONO ()
{/* 本函数用于打开文件,输入数据,调用函数,输出数据,关闭文件.*/
FILE *fp,*wf ;
int i ;
double x ;
fp = fopen("in.dat","r") ;
wf = fopen("out.dat","w") ;
for(i = 0 ; i < 10 ; i++) {
fscanf(fp,"%lf",&x) ;
fprintf(wf,"%lf
",fun(x)) ;
}
fclose(fp) ;
fclose(wf) ;
}
答案
s1=s1*n/(2*n+1);原因在于n设置的类型为int,不加括号时相当于s1=(s1*n)/(2*n+1);也就是s1=double/int所以结果自动转换为double型,就相当于是double/double,所以结果可以是小数.s1=s1*(n/(2*n+1));而(n/(2*n+1))加括...
举一反三
我想写一篇关于奥巴马的演讲的文章,写哪一篇好呢?为什么好
最新试题
热门考点