C library - tan() function



The C library tan() function returns the tangent of a given angle. This function has various real-life application across multiple field such as physics, astronomy, google map, engineering and many more.

Syntax

Following is the syntax of the C library function tan()

tan(double x);

Parameters

This function accepts only a single parameter −

  • x: The type double represents the angle in radian in which the tangent value is operated.

Return Value

This function returns the specified value of x.

Example 1

Following is the basic C program that illustrate the usage of tan() function.

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

int main() {
   double angle_degrees = 45.0;
   
   // Convert to radians
   double angle_radians = angle_degrees * M_PI / 180.0;  
   double tangent = tan(angle_radians);

   printf("The tangent of %.2f degrees is %.2f\n", angle_degrees, tangent);
   return 0;
}

Output

The above code produces the following result −

The tangent of 45.00 degrees is 1.00

Example 2

Here, we calculate the tangents of multiple angles in the form of an array.

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

int main() {
   double angles_degrees[] = {0, 30, 45, 60, 90};
   int size = sizeof(angles_degrees) / sizeof(angles_degrees[0]);

   printf("Angle (degrees) | Tangent\n");
   printf("****************|**********\n");
   for (int i = 0; i < size; i++) {
       double angle_radians = angles_degrees[i] * M_PI / 180.0;
       double tangent = tan(angle_radians);
       printf("%15.2f | %f\n", angles_degrees[i], tangent);
   }
   return 0;
}

Output

On execution of above code, we get the following result −

Angle (degrees) | Tangent
****************|**********
           0.00 | 0.000000
          30.00 | 0.577350
          45.00 | 1.000000
          60.00 | 1.732051
          90.00 | 16331239353195370.000000

Example 3

While handling the special cases say(infinity and NaN), it operates the various angles which may results in special values. Thus, it checks an infinity and NaN to print the specified value.

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

int main()
{
   double angles_radians[] = {M_PI / 4, M_PI / 2, M_PI, INFINITY, NAN};
   int size = sizeof(angles_radians) / sizeof(angles_radians[0]);

   printf("Angle (radians) | Tangent\n");
   printf("****************|**********\n");
   for (int i = 0; i < size; i++) {
       double tangent = tan(angles_radians[i]);
       if (isnan(tangent)) {
           printf("%15.2f | NaN\n", angles_radians[i]);
       } else if (isinf(tangent)) {
           printf("%15.2f | Infinity\n", angles_radians[i]);
       } else {
           printf("%15.2f | %f\n", angles_radians[i], tangent);
       }
    }

   return 0;
}

Output

The above code produces the following result −

Angle (radians) | Tangent
****************|**********
           0.79 | 1.000000
           1.57 | 16331239353195370.000000
           3.14 | -0.000000
            inf | NaN
            nan | NaN
math_h.htm
Advertisements