三角函数正弦、余弦和正切将三角形的角与其边联系起来。我们称之为 cos x 的余弦是邻边长度与斜边长度之比。
cos x = 邻边 / 斜边
通常,cos x 值与 sine x 值径向相反,因此 cos 0 = 1,cos 90 = 0。在本 C 语言程序中,我们将看到如何计算给定精度下的余弦 x 值。
在这个 C 语言程序中,我们将从用户那里接收到的度数值转换为弧度。我们还从用户的输入中获取精度。然后,我们使用一个 do-while 循环,根据公式计算 cos x 的值。
“do-while”循环一直工作到条件匹配(acc <= fabs(cosval - cosx)),然后我们计算 den 的值为 2*n*(2*n-1),它使用公式 -term * x * x / den 来查找项。然后我们使用公式 cosx + term 查找 cos x。此外,将 n 增加一。最后,我们使用 printf 语句显示结果。
步骤 1:导入头文件库,以使用 C 程序中使用的内置函数。
步骤 2:声明并定义 C 程序中使用的变量,包括 cos x 的值。
步骤 3:使用 printf 和 scanf 语句接受以度为单位的角度值。
步骤 4:使用公式将度数值转换为弧度。
步骤 5:使用 printf 和 scanf 从用户那里接受精度。
步骤 6:现在将 term = 1、cosx = term 和 n = 1 的值赋值。
步骤 7:打开一个 do while 循环,直到使用 C 语法满足条件。
步骤 8:在循环内部,计算“den”的值
步骤 9:使用“term”计算 cos x 的值,并将 n 增加 1。
步骤 10:打印 cos x 的结果。
此程序在 C 语言编程中使用以下概念,我们建议您阅读这些主题以更好地理解。
#include <stdio.h>
#include <math.h> /* include header files for accessing libraries */
#include <stdlib.h>
void main() {
int n, x1;
float acc, term, den, x, cosx = 0, cosval; /* declares cosx cosval etc variables */
printf("Enter the value of x (in degrees)\n"); /* accepts value of x in degree */
scanf("%f", & x);
x1 = x;
x = x * (3.142 / 180.0); /* Converting user input value from degrees to radians*/
cosval = cos(x);
printf("Enter the accuracy for the result\n");
scanf("%f", & acc);
term = 1;
cosx = term;
n = 1;
do {
den = 2 * n * (2 * n - 1);
term = -term * x * x / den; /* doing calculations inside the do while loop as same as sinx, please refer the sinx program for details */
cosx = cosx + term;
n = n + 1;
}
while (acc <= fabs(cosval - cosx));
printf("Sum of the cosine series = %f\n", cosx);
printf("Using Library function cos(%d) = %f\n", x1, cos(x));
} /*End of main() */
Enter the value of x (in degrees) 30 Enter the accuracy for the result 0.000001 Sum of the cosine series = 0.865991 Using Library function cos(30) = 0.865991 RUN 2 Enter the value of x (in degrees) 45 Enter the accuracy for the result 0.0001 Sum of the cosine series = 0.707031 Using Library function cos(45) = 0.707035