acos()
函数接受一个参数(1 ≥ x ≥ -1),并以弧度为单位返回其反余弦值。在数学上,acos(x) = cos-1(x)
。
acos()
函数包含在 <math.h>
头文件中。
acos() 原型
double acos(double x);
要查找 int
、float
或 long double
类型的反余弦值,您可以使用类型转换运算符显式将类型转换为 double
。
int x = 0; double result; result = acos(double(x));
此外,C99 中还引入了两个函数 acosf() 和 acosl(),分别专门用于处理 float
和 long double
类型。
float acosf(float x); long double acosl(long double x);
acos() 参数
acos()
函数接受一个范围在 [-1, +1] 之间的单个参数。这是因为余弦值的范围是 1 到 -1。
参数 | 描述 |
---|---|
double 值 | 必需。介于 -1 和 +1(含)之间的 double 值。 |
acos() 返回值
acos()
函数返回范围为 [0.0, π] 的弧度值。如果传递给 acos()
函数的参数小于 -1 或大于 1,该函数将返回 NaN(非数字)。
参数 (x) | 返回值 |
---|---|
x = [-1, +1] | [0, π] 弧度 |
-1 > x 或 x > 1 | NaN (非数字) |
示例 1:不同参数的 acos() 函数
#include <stdio.h>
#include <math.h>
int main()
{
// constant PI is defined
const double PI = 3.1415926;
double x, result;
x = -0.5;
result = acos(x);
printf("Inverse of cos(%.2f) = %.2lf in radians\n", x, result);
// converting radians to degree
result = acos(x)*180/PI;
printf("Inverse of cos(%.2f) = %.2lf in degrees\n", x, result);
// paramter not in range
x = 1.2;
result = acos(x);
printf("Inverse of cos(%.2f) = %.2lf", x, result);
return 0;
}
输出
Inverse of cos(-0.50) = 2.09 in radians Inverse of cos(-0.50) = 120.00 in degrees Inverse of cos(1.20) = nan
示例 2:acosf() 和 acosl() 函数
#include <stdio.h>
#include <math.h>
int main()
{
float fx, facosx;
long double lx, ldacosx;
// arc cosine of type float
fx = -0.505405;
facosx = acosf(fx);
// arc cosine of type long double
lx = -0.50540593;
ldacosx = acosf(lx);
printf("acosf(x) = %f in radians\n", facosx);
printf("acosl(x) = %Lf in radians", ldacosx);
return 0;
}
输出
acosf(x) = 2.100648 in radians acosl(x) = 2.100649 in radians