cos, cosf, cosl

< c‎ | numeric‎ | math
在标头 <math.h> 定义
float       cosf( float arg );
(1) (C99 起)
double      cos( double arg );
(2)
long double cosl( long double arg );
(3) (C99 起)
_Decimal32  cosd32( _Decimal32 arg );
(4) (C23 起)
_Decimal64  cosd64( _Decimal64 arg );
(5) (C23 起)
_Decimal128 cosd128( _Decimal128 arg );
(6) (C23 起)
在标头 <tgmath.h> 定义
#define cos( arg )
(7) (C99 起)
1-6) 计算 arg (以弧度计量)的余弦。
7) 泛型宏:若实参拥有 long double 类型,则调用 cosl。否则,若实参拥有整数类型或 double 类型,则调用 cos。否则,调用 cosf、若实参为复数,则该宏调用对应的复函数(ccosfccosccosl)。

参数

arg - 以弧度表示角的浮点值

返回值

若不出现错误,则返回 arg 的余弦(cos(arg)),在范围 [-1 ; +1] 中。

arg 的绝对值很大,则结果可能只有少量或没有效数字。

(C99 前)

若出现定义域错误,则返回实现定义值(受支持平台上为 NaN)。

若出现下溢所致的值域错误,则返回(舍入后的)正确的结果。

错误处理

报告 math_errhandling 中指定的错误。

若实现支持 IEEE 浮点算术(IEC 60559),

  • 则若参数为 ±0,则结果为 1.0
  • 若参数为 ±∞,则返回 NaN 并引发 FE_INVALID
  • 若参数为 NaN,则返回 NaN

注意

参数为无穷大的情况不被指定为 C 中的定义域错误,但被定义为 POSIX 中的定义域错误

示例

#include <errno.h>
#include <fenv.h>
#include <math.h>
#include <stdio.h>
 
#ifndef __GNUC__
#pragma STDC FENV_ACCESS ON
#endif
 
int main(void)
{
    const double pi = acos(-1);
 
    // 典型用法
    printf("cos(pi/3) = %f\n", cos(pi / 3));
    printf("cos(pi/2) = %f\n", cos(pi / 2));
    printf("cos(-3*pi/4) = %f\n", cos(-3 * pi / 4));
 
    // 特殊值
    printf("cos(+0) = %f\n", cos(0.0));
    printf("cos(-0) = %f\n", cos(-0.0));
 
    // 错误处理
    feclearexcept(FE_ALL_EXCEPT);
    printf("cos(INFINITY) = %f\n", cos(INFINITY));
    if (fetestexcept(FE_INVALID))
        puts("    FE_INVALID raised");
}

可能的输出:

cos(pi/3) = 0.500000
cos(pi/2) = 0.000000
cos(-3*pi/4) = -0.707107
cos(+0) = 1.000000
cos(-0) = 1.000000
cos(INFINITY) = -nan
    FE_INVALID raised

引用

  • C23 标准(ISO/IEC 9899:2024):
  • 7.12.4.5 The cos functions (第 TBD 页)
  • 7.25 Type-generic math <tgmath.h> (第 TBD 页)
  • F.10.1.5 The cos functions (第 TBD 页)
  • C17 标准(ISO/IEC 9899:2018):
  • 7.12.4.5 The cos functions (第 174 页)
  • 7.25 Type-generic math <tgmath.h> (第 272-273 页)
  • F.10.1.5 The cos functions (第 378 页)
  • C11 标准(ISO/IEC 9899:2011):
  • 7.12.4.5 The cos functions (第 239 页)
  • 7.25 Type-generic math <tgmath.h> (第 373-375 页)
  • F.10.1.5 The cos functions (第 519 页)
  • C99 标准(ISO/IEC 9899:1999):
  • 7.12.4.5 The cos functions (第 220 页)
  • 7.22 Type-generic math <tgmath.h> (第 335-337 页)
  • F.9.1.5 The cos functions (第 456 页)
  • C89/C90 标准(ISO/IEC 9899:1990):
  • 4.5.2.5 The cos function

参阅

(C99)(C99)
计算正弦(sin(x)
(函数)
(C99)(C99)
计算正切(tan(x)
(函数)
(C99)(C99)
计算反余弦(arccos(x)
(函数)
(C99)(C99)(C99)
计算复数余弦
(函数)