本帖最后由 jackz007 于 2021-10-21 00:58 编辑 #include <stdio.h>
#include <math.h>
/* 本程序利用泰勒级数近似计算 sin(x) 和 cos(x) 的数值,精确到 10e-5 */
/* 算法参考:http://www.ab126.com/shuxue/3820.html */
double sinx(double x)
{
long long b , i , j , s ;
double e , v ;
for(e = 1.0 , s = 1 , v = 0.0 , i = 1 ; e >= 0.00001 ; i += 2 , s = - s) {
for(b = 1 , j = i ; j ; j --) b *= j ;
e = pow(x , i) / b ;
v += s * e ;
}
return v ;
}
double cosx(double x)
{
long long b , i , j , s ;
double e , v ;
for(e = v = 1.0 , s = -1 , i = 2 ; e >= 0.00001 ; i += 2 , s = - s) {
for(b = 1 , j = i ; j ; j --) b *= j ;
e = pow(x , i) / b ;
v += s * e ;
}
return v ;
}
int main(void)
{
double x = 0.0 ;
printf("sin(%lf) = %lf\n" , x , sinx(x)) ;
printf("cos(%lf) = %lf\n" , x , cosx(x)) ;
x = M_PI / 6 ;
printf("sin(%lf) = %lf\n" , x , sinx(x)) ;
printf("cos(%lf) = %lf\n" , x , cosx(x)) ;
x = M_PI / 3 ;
printf("sin(%lf) = %lf\n" , x , sinx(x)) ;
printf("cos(%lf) = %lf\n" , x , cosx(x)) ;
x = M_PI / 2 ;
printf("sin(%lf) = %lf\n" , x , sinx(x)) ;
printf("cos(%lf) = %lf\n" , x , cosx(x)) ;
}
编译、运行实况:D:\00.Excise\C>g++ -o x x.c
D:\00.Excise\C>x
sin(0.000000) = 0.000000
cos(0.000000) = 1.000000
sin(0.523599) = 0.500000
cos(0.523599) = 0.866025
sin(1.047198) = 0.866025
cos(1.047198) = 0.500000
sin(1.570796) = 1.000000
cos(1.570796) = 0.000000
D:\00.Excise\C>
|