用C语言编写一个利用展开式求余弦函数近似值的程序。
时间: 2024-03-08 14:48:45 浏览: 33
以下是用展开式求余弦函数近似值的C语言程序:
```c
#include <stdio.h>
#include <math.h>
double cos_approx(double x, double e) {
double res = 0.0, term = 1.0;
int i = 0;
while (fabs(term) >= e) {
res += term;
i += 2;
term *= -x * x / ((double)i * (i - 1));
}
return res;
}
int main() {
double x, e;
printf("请输入x和精度e:\n");
scanf("%lf%lf", &x, &e);
printf("cos(%lf)的近似值为:%lf\n", x, cos_approx(x, e));
return 0;
}
```
程序中的 `cos_approx` 函数用于计算余弦函数的近似值。它采用了 while 循环,每次将当前项加入结果中,然后计算下一项,直到最后一项的绝对值小于精度 e,此时循环结束,返回结果。
在主函数中,首先获取用户输入的 x 和精度 e,然后调用 `cos_approx` 函数计算余弦函数的近似值,并输出结果。
注意,此程序中需要用到 math.h 头文件中的 fabs 函数,用于计算绝对值。
相关问题
用c语言编写一个利用展开式求余弦函数近似值的程序,余弦函数近似值:输入精度e,用余弦公式求cos的近似值,精确到最后一项的绝对值小于e(注:当最后一项的绝对值小于e时,该项不再进行累加)。
以下是一个利用泰勒展开式求余弦函数近似值的 C 语言程序:
```
#include <stdio.h>
#include <math.h>
double cos_approx(double x, double e);
int main() {
double x, e;
printf("请输入角度(度)和精度:");
scanf("%lf %lf", &x, &e);
double rad = x * M_PI / 180.0; // 角度转弧度
double cos_x = cos(rad);
double cos_e = cos_approx(rad, e);
printf("cos(%lf) 的真实值为 %lf\n", x, cos_x);
printf("精度为 %lf 时的近似值为 %lf\n", e, cos_e);
return 0;
}
double cos_approx(double x, double e) {
double term = 1.0, sum = 1.0;
int i;
for (i = 1; fabs(term) >= e; i += 2) {
term *= -x * x / (i * (i + 1));
sum += term;
}
return sum;
}
```
程序中的 `cos_approx` 函数利用泰勒展开式求余弦函数的近似值,直到最后一项的绝对值小于精度 `e` 为止。函数中使用了 `for` 循环来依次累加每一项,同时使用 `fabs` 函数来计算绝对值。
在主函数中,先输入角度和精度,然后将角度转换为弧度,使用 `cos` 函数计算余弦函数的真实值,再调用 `cos_approx` 函数计算近似值,并输出结果。
注意:本程序中的角度转弧度需要用到 `math.h` 头文件中的宏定义 `M_PI`,因此需要在编译时链接数学库,例如使用 gcc 编译时需要添加 `-lm` 参数。
用c语言编写一个利用展开式求余弦函数近似值且用公式cos(x)= 0! x 0 − 2! x 2 + 4! x 4 − 6! x 6 +…表达的程序
以下是用C语言编写的利用展开式求余弦函数近似值的程序:
```c
#include <stdio.h>
#include <math.h>
double cos_approx(double x) {
double sum = 1.0, term = 1.0;
int i;
for (i = 1; i <= 6; i++) {
term *= -x * x / ((2 * i - 1) * 2 * i);
sum += term;
}
return sum;
}
int main() {
double x, cos_x;
printf("Enter the value of x in radians: ");
scanf("%lf", &x);
cos_x = cos_approx(x);
printf("cos(%lf) = %lf\n", x, cos_x);
return 0;
}
```
在这个程序中,我们定义了一个 `cos_approx` 函数,它使用展开式计算余弦函数的近似值。该函数使用一个循环来计算展开式的每一项,并将它们相加得到最终的近似值。我们在主函数中调用该函数,将用户输入的角度值传递给它。最后,我们输出计算得到的近似余弦值。
注意:在使用这个程序时,需要将用户输入的角度值转换为弧度值,因为 `cos_approx` 函数使用的是弧度值。可以使用 `math.h` 头文件中的 `double rad = deg * M_PI / 180.0;` 将角度值转换为弧度值。