用台劳多项式求cosx近似值的C语言代码
时间: 2023-05-28 21:06:25 浏览: 180
以下是使用台劳多项式求cosx近似值的C语言代码:
```c
#include <stdio.h>
#include <math.h>
double cos_taylor(double x, int n) {
double cos_x = 1.0;
double term = 1.0;
int i;
for (i = 1; i <= n; i++) {
term *= -x * x / ((2 * i - 1) * (2 * i));
cos_x += term;
}
return cos_x;
}
int main() {
double x, cos_x;
int n;
printf("Enter a value for x (in radians): ");
scanf("%lf", &x);
printf("Enter the number of terms in the Taylor series: ");
scanf("%d", &n);
cos_x = cos_taylor(x, n);
printf("cos(%lf) = %lf\n", x, cos_x);
printf("The actual value of cos(%lf) is %lf\n", x, cos(x));
return 0;
}
```
这个程序要求用户输入一个角度值x(以弧度为单位),以及Taylor级数中使用的项数n。然后,它使用cos_taylor函数计算cos(x)的近似值,并将其打印到屏幕上。最后,程序打印出实际值cos(x)和近似值之间的误差。
阅读全文