记录一些c小程的傻x错误
一、本题要求实现一个函数,用下列公式求cos(x)的近似值,精确到最后一项的绝对值小于e:
\[cos(x)=x^0/0!−x^2/2!+x^4/4!−x^6/6!+⋯
\]
错误做法:
double funcos( double e, double x ){
double now=1,res=0;
for(int i=0,sg=1;i<30000000;i++,sg*=-1){
res+=sg*now;
now=now*x/(double)(i*2+1)*x/(double)(i*2+2);
}
return res;
}
要注意到double类型中0可能会是eps,所以本来应该是10000个0相加,就变成了10000个eps相加。
修改:
double funcos( double e, double x ){
double now=1,res=0;
for(int i=0,sg=1;i<30000000;i++,sg*=-1){
res+=sg*now;
now=now*x/(double)(i*2+1)*x/(double)(i*2+2);
if(now*10<e) break;
}
return res;
}
二、

浙公网安备 33010602011771号