C 语言程序求 Sinx 的值到给定精度


2022 年 4 月 11 日, Learn eTutorial
2942

什么是 sinx 三角函数?

正弦是直角三角形的一个三角角度,在这个 C 语言程序中,我们将计算 正弦 x 的值到给定精度。对于一个角度,正弦值定义为该角度对边长度与斜边长度的比值。[斜边指三角形最长的一边]。
通常所有三角函数都定义为三角形边的比值,它们也有一个角度。定义角度的正弦值为 正弦 0 = 0正弦 90 = 1正弦 30 = .5 等。
在这里,我们将计算 正弦 x 的值到给定精度。为此,我们首先将给定度数转换为弧度。我们使用 do-while 循环并使用以下步骤。

         den = 2*n*(2*n+1);
         term = -term * x * x / den;
         sinx = sinx + term;
         n = n + 1;

sinx 计算如何使用 C 语言实现?

在此 C 程序中,导入头文件后,我们接受 x 的度数值。我们将其保存到一个变量中,现在要应用公式,我们需要使用公式 'pi / 180' 将度数转换为弧度。我们从用户那里获取所需的精度,并将弧度角的变量值 'x' 保存起来,然后将 'x' 复制到另一个变量并将其赋值给 sin(x)。现在打开一个 do-while 循环来检查并使用 den =2*n*(2*n+1) 计算值,然后使用 'den' 计算 term = -term * x * x / den; 。然后 sinx - sinx = sinx + term; 我们一直循环直到条件 acc <= fabs(sinval - sinx) 为真。最后打印 sinx 的值作为结果。

算法

步骤 1: 将头文件导入 C 程序以使用内置函数。

步骤 2: 使用 printfscanf 接受角度的度数值,并将其保存到变量中。

步骤 3: 初始化和定义变量。

步骤 4: 将角度的度数值保存到变量中,并使用 'pi / 180' 将角度转换为弧度。

步骤 5: 使用 sinvalsin(x) 的值赋给变量。

步骤 6: 使用 printfscanf 接受用户输入的精度值,并将其保存到变量中。

步骤 7: 保存 term =xsinx = term 以及 n = 1 的值。

步骤 8:打开一个 'do while' 循环条件,直到条件满足 (acc <= fabs(sinval - sinx))。

步骤 9: 使用公式 den = 2*n*(2*n+1) 计算 'den' 的值。

步骤 10: 使用公式 -term * x * x / den 计算项值。使用该值,通过 sinx + term 计算 sinx 的值,并将 n 增加 1

步骤 11: 使用 printf 打印正弦级数的结果。


此三角函数程序使用以下 C 语言编程概念,请参阅这些主题以获得更好的理解

C 语言源代码

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

void main()
     { 
         int n, x1;
         float  acc, term, den, x, sinx=0, sinval;  /* declares acc, term, den, sinx, sinval as float */
         printf("Enter the value of x (in degrees)\n");  /* gets the value of x in degrees */
         scanf("%f",&x);
         x1 = x;
         x = x*(3.142/180.0);   /* Converting degrees to radians*/           
         sinval = sin(x);
         printf("Enter the accuracy for the result\n");   /* receives value of accuracy */
         scanf("%f", & acc);
         term = x;
         sinx = term;
         n = 1;

         /* enters do while loop and use the formula to find den */
         do   
            {
                 den = 2*n*(2*n+1);
                 term = -term * x * x / den;    
                 sinx = sinx + term;   
                 n = n + 1;
            } while(acc <= fabs(sinval - sinx));    /* while condition checking */
         printf("Sum of the sine series         = %f\n", sinx);
         printf("Using Library function sin(%d) = %f\n", x1,sin(x));  /* prints the value of sinx */
    }                                                                
                                      

输出

Enter the value of x (in degrees)
30
Enter the accuracy for the result
0.000001
Sum of the sine series         = 0.500059
Using Library function sin(30) = 0.500059

RUN 2

Enter the value of x (in degrees)
45
Enter the accuracy for the result
0.0001
Sum of the sine series         = 0.707215
Using Library function sin(45) = 0.707179