C Library Function - acos()
Description
acos() is a function in the C standard library used to compute the arc cosine of a number (also known as the inverse cosine function among the inverse trigonometric functions).
acos()The function takes a real number between -1 and 1 and returns its arc cosine in radians.
Declaration
Here is the declaration of the acos() function.
#include
double acos(double x);
float acosf(float x);
long double acosl(long double x);
Parameters
- x -- A floating-point number between -1 and 1.
Return Value
- Return
xThe arc cosine value, in radians. The return value ranges over [0, PI]. - If both the
xis not in the range [-1, 1], the function returns NaN and sets an appropriate math error (such asEDOM).
Example
The following example demonstrates the use of the acos() function.
Example
#include
#include
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
and. - Define a variable
x, with the value 0.5. - Use
acos()Computexthe arc cosine of, and stores the result inresultit. - Print
xthe arc cosine of, in radians. - Convert the result to degrees and print it. The conversion formula is
弧度 * (180 / π).
Let's 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 input x is outside the valid range [-1, 1],acos() will return NaN and set errno is EDOM. You can use isnan() to check whether the result is NaN:
Example
#include
#include
#include
int
main
(
)
{
double
x
=
2.0
;
// Invalid input, outside the [-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 tries to compute
acos(2.0), which is an invalid input because 2.0 is not in the [-1, 1] range. errnois reset to 0, then callacos(x).- Checks
errnois equal toEDOM, and if so, print an error message. - If there is no error, print the computation result.
Let's compile and run the above program, which will produce the following result:
acos(2.000000) = nan radians
acos() The function computes the arc cosine of a given value and is a common tool for inverse trigonometric operations. When using it, make sure the input value is in the range [-1, 1] and handle possible error conditions. By converting the result to degrees, you can understand it more intuitively.
C Standard Library -