C语言计算Cos(x)级数和的程序


2022年4月2日, 学习e教程
3662

什么是cos x级数?

三角函数用于将三角形的边与角关联起来。余弦,我们称之为 cosx,是邻边长度与斜边长度的比值。“cosA = 邻边/斜边”。

cos X级数包含偶数幂和阶乘。通常,余弦级数的公式是:

cosx = 1 - (x^2/2!) + (x^4/4!) - (x^6/6!) + ..........

在这个C语言程序中,我们从用户那里获取角度的输入(以度为单位),并将其转换为弧度进行计算。然后,我们打开一个for循环,使用公式cosx = cosx + (pow (x,i) /fact) *sign ; sign = sign *(-1); 来计算cos x的和。为了使用pow()函数,我们必须在程序中包含“math.h”头文件。这是一个易于理解的简单程序。这里我们使用了for循环

算法

步骤1:包含头文件以使用C语言程序中的内置函数。

步骤2:声明整型变量n, x1, i, j

步骤3:声明变量xsigncosxfactfloat类型。

步骤4:将级数的项数读取到变量n中。

步骤5:将角度值读取到变量x中。

步骤6:x1=x

步骤7:x=x*(3.142/180.0)

步骤8:cosx=1sign=-1i=2

步骤9:使用条件为“i<=n”的for循环,当条件为真时,执行步骤10至13,每次将i增加1。

步骤10:设置fact=1

步骤11:使用另一个条件为“j<=i”的for循环,执行fact=fact*j,每次将j增加1。

步骤12:cosx=cosx+(pow(x,i)/fact)*sign

步骤13:sign=sign*(-1)

步骤14:显示余弦级数的和为cosx

步骤15:使用库函数cos(x)显示cos(x1)的值。


此余弦级数程序使用了循环概念。有关C语言循环的更多信息,请点击此处

C 语言源代码

                                          #include<stdio.h>
#include<math.h>

void main() {
    int n, x1, i, j;
    float x, sign, cosx, fact;
    printf("Enter the number of the terms in a series\n"); 
    scanf("%d", & n);
    printf("Enter the value of x(in degrees)\n");
    scanf("%f", & x);
    x1 = x;
    x = x * (3.142 / 180.0); /* Degrees to radians*/ /* converting the degrees into radians */
    cosx = 1;
    sign = -1;
    for (i = 2; i <= n; i = i + 2) {
      fact = 1;
      for (j = 1; j <= i; j++) {
        fact = fact * j;
      }
      cosx = cosx + (pow(x, i) / fact) * sign; /* calculating the cosx x sum */
      sign = sign * (-1);
    }
    printf("Sum of the cosine series= %7.2f\n", cosx);     
    printf("The value of cos(%d) using library method = %f\n", x1, cos(x));
 
    } /*End of main() */
                                      

输出

Enter the number of the terms in a series
5

Enter the value of x(in degrees)
60
Sum of the cosine series                    =    0.50  
The value of cos(60) using library method = 0.499882