为什么这调用函数里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("
来源:学生作业帮助网 编辑:六六作业网 时间:2024/12/18 23:54:12
为什么这调用函数里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("
为什么这调用函数里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("\neps = %lf,PI=%lf\n",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\n",fun(x)) ;
}
fclose(fp) ;
fclose(wf) ;
}
为什么这调用函数里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("
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))加括号后先计算的是n/(2*n+1)也就是int/int,结果还是int类型,这时假如是2/5那么括号里面(n/(2*n+1))就会出问题,因为2/5除不尽,所以其值为0,既是自动舍弃小数部分.