C library - acos() function



The C library acos() function returns the arc cosine of x in radians.

This parameter must be in the range of -1 to 1 and if the given input set to out of range, it will return nan and may errno to EDOM.

Syntax

Following is the C library syntax of the acos() function −

double acos(double x)

Parameters

This function takes only single parameter −

  • x − This is the floating point value in the interval [-1,+1].

Return Value

This function returns principal arc cosine of x, in the interval [0, pi] radians else it returns the values as nan(not a number).

Example 1

Following is the basic C library program to see the demonstration of acos() function.

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

#define PI 3.14159265

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

   x = 0.9;
   val = 180.0 / PI;

   ret = acos(x) * val;
   printf("The arc cosine of %lf is %lf degrees", x, ret);
   
   return(0);
}

Output

The above code produces the following result −

The arc cosine of 0.900000 is 25.855040 degrees

Example 2

Below the program illustrates the usage of acos() where the arguments are x > 1 or x < -1 and it will results the value as nan.

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

int main()
{
   double x = 4.4, res;

   // Function call to calculate acos(x) value
   res = acos(x);

   printf("acos(4.4) = %f radians\n", res);
   printf("acos(4.4) = %f degrees\n", res * 180 / 3.141592);

   return 0;
}

Output

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

acos(4.4) = nan radians
acos(4.4) = nan degrees

Example 3

Here, we set the macros in numerical range between 1 to -1 to check whether the given number is exists under the range or not.

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
 
#define MAX  1.0
#define MIN -1.0
 
int main(void)
{
   double x = 10, y = -1; 
   
   y = acos(x);
   if (x > MAX)
     printf( "Error: %lf not in the range!\n", x );
   else if (x < MIN)
     printf( "Error: %lf not in the range!\n", x );
   else 
     printf("acos(%lf) = %lf\n", x, y);
}

Output

After executing the above code, we get the following result −

Error: 10.000000 not in the range!
Advertisements