本題要求實現一個函數,用下列公式求cos的近似值,精確到最后一項的絕對值小於e:
cos
函數接口定義:
double funcos( double e, double x );
其中用戶傳入的參數為誤差上限e
和自變量x
;函數funcos
應返回用給定公式計算出來、並且滿足誤差要求的cos的近似值。輸入輸出均在雙精度范圍內。
裁判測試程序樣例:
#include <stdio.h> #include <math.h> double funcos( double e, double x ); int main() { double e, x; scanf("%lf %lf", &e, &x); printf("cos(%.2f) = %.6f\n", x, funcos(e, x)); return 0; } /* 你的代碼將被嵌在這里 */
輸入樣例:
0.01 -3.14
輸出樣例:
cos(-3.14) = -0.999899
double funcos( double e, double x ) { int i,k; double tmp1,tmp2,tmp3,sum; tmp1=1,tmp2=1,tmp3=1,sum=1; k=-1; for(i=2;e<tmp3;i+=2){ tmp1 = tmp1*x*x; tmp2 = tmp2*i*(i-1); sum+=k*tmp1/tmp2; tmp3=tmp1/tmp2; k=-k; } return sum; }