C library functions -acos()
Description
acos()is the C standard library<math.h>a function used to calculate the arccosine value of a number (also known as the cosine inverse function among inverse trigonometric functions).
acos()The function accepts a real number between -1 and 1 and returns the arccosine of that value, in radians.
Declaration
Below is the declaration of the acos() function.
#include <math.h> double acos(double x); float acosf(float x); long double acosl(long double x);
Parameter
- x-- a floating-point number between -1 and 1.
Return Value
- return
xThe arccosine value, in radians. The range of the return value is [0, π]. - if
xIf it is not within the range [-1, 1], the function will return NaN and set an appropriate math error (for example,EDOM)。
Example
The following example demonstrates the usage of the acos() function.
Example
#include <math.h>
int main() {
double x = 0.5;
double result = acos(x);
printf("acos(%f) = %f radians\n", x, result);
printf("acos(%f) = %f degrees\n", x, result * 180 / M_PI);
return 0;
}
Code Analysis:
- The code first includes the header file.
<math.h>and<stdio.h>。 - define a variable
x, the value is 0.5. - Usage
acos()Computexarc cosine value, and stores the result inresultIn. - print
xthe arc cosine value, in radians. - Convert the result to degrees, and print it out. The conversion formula is:
弧度 * (180 / π)。
Let us compile and run the above program, which will produce the following result:
acos(0.500000) = 1.047198 radians acos(0.500000) = 60.000000 degrees
Error Handling
If the inputxexceeding the valid range [-1, 1],acos()will return NaN and seterrnoisEDOM. You can useisnan()The function checks whether the result is NaN:
Example
#include <math.h>
#include <errno.h>
int main() {
double x = 2.0; // Invalid input, out of [-1, 1] range
errno = 0; // Reset errno
double result = acos(x);
if (errno == EDOM) {
printf("Input value is out of domain. acos(%f) is not defined.\n", x);
} else {
printf("acos(%f) = %f radians\n", x, result);
}
return 0;
}
Code Analysis:
- The code attempts to calculate
acos(2.0), this is an invalid input, because 2.0 is not within the range [-1, 1]. errnois reset to 0, then callacos(x)。- Checks
errnoWhether it equalsEDOM, if so, print an error message. - If there are no errors, the calculation result is printed.
Let us compile and run the above program, which will produce the following result:
acos(2.000000) = nan radians
acos()The function is used to calculate the arc cosine of a given value, and is a common tool for handling inverse trigonometric operations. When using it, ensure that the input value is within the range [-1, 1], and handle possible error conditions. By converting the result to degrees, the result can be understood more intuitively.