求cosx的近似值c语言
时间: 2023-07-13 16:36:40 浏览: 74
可以使用泰勒级数展开来求解cosx的近似值,代码如下:
```c
#include <stdio.h>
#include <math.h>
double cosx(double x, int n) {
double res = 1.0;
int i, j, sign = 1;
for (i = 1, j = 2; i <= n; i++, j += 2) {
res += sign * pow(x, j) / factorial(j);
sign *= -1;
}
return res;
}
int factorial(int n) {
int res = 1;
for (int i = 2; i <= n; i++) {
res *= i;
}
return res;
}
int main() {
double x = 1.0;
int n = 10;
printf("cos(%.2f) = %.6f\n", x, cos(x));
printf("cos(%.2f) ≈ %.6f\n", x, cosx(x, n));
return 0;
}
```
其中,cosx函数使用泰勒级数展开的方式求解cosx的近似值,factorial函数用于求解阶乘。在main函数中,可以设置x和n的值,分别表示要求解的cosx的值和泰勒级数展开的项数,从而得到cosx的精确值和近似值。
相关问题
用台劳多项式求cosx近似值的C语言代码
以下是使用台劳多项式求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)和近似值之间的误差。
用台劳多项式求cosx的近似值c语言程序
以下是使用台劳多项式求cosx的近似值的C语言程序:
```c
#include <stdio.h>
#include <math.h>
double Tn(int n, double x) {
if (n == 0) {
return 1.0;
} else if (n == 1) {
return x;
} else {
return 2 * x * Tn(n-1, x) - Tn(n-2, x);
}
}
int main() {
double x, sum = 0.0;
int i, n;
printf("Enter the value of x in radians: ");
scanf("%lf", &x);
printf("Enter the number of terms in the series: ");
scanf("%d", &n);
for (i = 0; i <= n; i++) {
sum += pow(-1, i) * Tn(2*i, x) / factorial(2*i);
}
printf("cos(%lf) = %lf\n", x, sum);
return 0;
}
```
在这个程序中,我们使用了递归函数 `Tn` 来计算台劳多项式。然后,我们在主函数中使用一个循环来计算cosx的近似值,并将其打印出来。
需要注意的是,这个程序中使用了 `factorial` 函数,它在程序中未被定义。你需要自己实现一个阶乘函数来计算分母上的阶乘。