2025年3月17日 星期一 甲辰(龙)年 月十六 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 编程开发 > VC/VC++

acos()_C语言acos()详解:反余弦函数,求反余弦值

时间:12-25来源:作者:点击数:123

double acos(double x);

acos() 函数的功能是求反余弦值。

反余弦函数 acos() 和余弦函数 cos() 的功能恰好相反:cos() 是已知一个角的弧度值 x,求该角的余弦值 y;而 acos() 是已知一个角的余弦值 y,求该角的弧度值 x。

参数

返回值

正常情况下(x 的取值位于区间[-1, 1]),函数返回余弦值为 x 的角的弧度数。

如果 x 的取值超出范围,那么 acos() 将发生域错误,此时返回值为 NaN

发生域错误时,acos() 还会设置 <errno.h> 头文件下的 errno 和 <fenv.h> 头文件下的 FE_INVALID,我们也可以借此检测出域错误。关于域错误的更多内容请猛击《域错误(domain error)》。

实例

【实例1】求 0.5 的反余弦值(正常情况)。

  • /* acos example */
  • #include <stdio.h> /* printf */
  • #include <math.h> /* acos */
  • #define PI 3.14159265
  • int main ()
  • {
  • double param, result;
  • param = 0.5;
  • result = acos (param) * 180.0 / PI; //将弧度转换为度
  • printf ("The arc cosine of %f is %f degrees.\n", param, result);
  • return 0;
  • }

运行结果:

The arc cosine of 0.500000 is 60.000000 degrees.

【实例2】求 2 的反余弦值(发生域错误)。

  • /* acos example */
  • #include <stdio.h> /* printf */
  • #include <math.h> /* acos */
  • #include <errno.h> /* errno */
  • #include <fenv.h> /* FE_INVALID */
  • #define PI 3.14159265
  • int main()
  • {
  • double result;
  • result = acos(2) * 180.0 / PI;
  • printf("result is :%f\n", result);
  • if (errno == EDOM) {
  • perror("errno == EDOM");
  • }
  • if (fetestexcept(FE_INVALID)) {
  • printf("FE_INVALID is set\n");
  • }
  • return 0;
  • }

在 VS2015 下的运行结果:

result is :-nan(ind)
errno == EDOM: Domain error
FE_INVALID is set

在 GCC 下的运行结果:

result is :nan
errno == EDOM: Numerical argument out of domain
FE_INVALID is set

在 Xcode 下的运行结果:

result is :nan
FE_INVALID is set

不同的编译器对 NaN 的输出不同,具体原因请猛击《NaN(Not a Number),表示一个无效数字》。

Xcode 使用了较新的 C99 标准,当发生域错误时,不再设置 errno 的值了。

方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门