C library functions -cos()

C standard library - <math.h>

Description

C Library Functionsdouble cos(double x)Returns the radian anglexThe cosine of.

cos()is the C standard library<math.h>A function used to calculate the cosine of an angle (in radians). This function is very commonly used in trigonometric calculations involving mathematical computations, physical simulations, and engineering applications.

Declaration

Below is the declaration of the cos() function.

#include <math.h>

double cos(double x);
float cosf(float x);
long double cosl(long double x);

Parameter

  • x: The angle in radians, of typedouble、floatorlong double。

Return Value

returnxThe cosine value, with a range of [-1, 1].

Example

The following example demonstrates the usage of the cos() function.

Example

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

#define PI 3.14159265

int main ()
{
   double x, ret, val;

   x = 60.0;
   val = PI / 180.0;
   ret = cos( x*val );
   printf("The cosine of %lf is %lf degrees\n", x, ret);
   
   x = 90.0;
   val = PI / 180.0;
   ret = cos( x*val );
   printf("The cosine of %lf is %lf degrees\n", x, ret);
   
   return(0);
}

Let's compile and run the above program, which will produce the following result:

60.000000 的余弦是 0.500000 度
90.000000 的余弦是 0.000000 度

Compute the cosine values of different angles

The following example demonstrates how to calculate the cosine of multiple angles:

Example

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

int main() {
    double angles[] = {0, M_PI / 6, M_PI / 4, M_PI / 3, M_PI / 2, M_PI};
    const char* angle_labels[] = {"0", "π/6", "π/4", "π/3", "π/2", "π"};
    int num_angles = sizeof(angles) / sizeof(angles[0]);

    for (int i = 0; i < num_angles; i++) {
        double angle = angles[i];
        double result = cos(angle);
        printf("cos(%s) = %f\n", angle_labels[i], result);
    }

    return 0;
}

Code Analysis:

  • Define an array containing multiple anglesangles, each angle expressed in radians.
  • Define a corresponding label arrayangle_labels, used for printing output.
  • UsageforLoop through each angle, compute the cosine value and print the result.

Let's compile and run the above program, which will produce the following result:

cos(0) = 1.000000
cos(π/6) = 0.866025
cos(π/4) = 0.707107
cos(π/3) = 0.500000
cos(π/2) = 0.000000
cos(π) = -1.000000

Error Handling

cos()The function is valid for all real-number inputs, so no special error handling is required. The function does not seterrno, nor will it return NaN, unless the input itself is NaN or infinity. In this case, the returned result will be NaN.

Summary

cos()The function is used to calculate the cosine of a given angle (in radians) and is an important tool for handling trigonometric operations. Through reasonable usecos()function, can obtain accurate results in mathematical calculations, physical simulations, and engineering applications.

C standard library - <math.h>

other extensions