Namespaces
Variants

std:: tan, std:: tanf, std:: tanl

From cppreference.net
Common mathematical functions
Nearest integer floating point operations
(C++11)
(C++11)
(C++11) (C++11) (C++11)
Floating point manipulation functions
(C++11) (C++11)
(C++11)
(C++11)
Classification and comparison
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
Types
(C++11)
(C++11)
(C++11)
Macro constants
定义于头文件 <cmath>
(1)
float tan ( float num ) ;

double tan ( double num ) ;

long double tan ( long double num ) ;
(C++23 前)
/*floating-point-type*/
tan ( /*floating-point-type*/ num ) ;
(C++23 起)
(C++26 起为 constexpr)
float tanf ( float num ) ;
(2) (C++11 起)
(C++26 起为 constexpr)
long double tanl ( long double num ) ;
(3) (C++11 起)
(C++26 起为 constexpr)
SIMD 重载 (C++26 起)
定义于头文件 <simd>
template < /*math-floating-point*/ V >

constexpr /*deduced-simd-t*/ < V >

tan ( const V & v_num ) ;
(S) (C++26 起)
额外重载 (C++11 起)
定义于头文件 <cmath>
template < class Integer >
double tan ( Integer num ) ;
(A) (C++26 起为 constexpr)
1-3) 计算 num (以弧度计量)的正切值。 库为所有 cv 未限定浮点类型提供了 std::tan 的重载版本作为参数类型。 (C++23 起)
S) SIMD 重载对 v_num 执行逐元素的 std::tan 运算。
(参见 math-floating-point deduced-simd-t 了解其定义。)
(since C++26)
A) 为所有整数类型提供了额外的重载,这些类型被视为 double
(since C++11)

目录

参数

num - 表示角度(以弧度为单位)的浮点数或整数值

返回值

如果未发生错误,则返回 num 的正切值( tan(num) )。

num 的幅值较大,则结果可能几乎没有意义或毫无意义。

(until C++11)

如果发生定义域错误,将返回一个由实现定义的值(在支持 NaN 的情况下返回 NaN)。

如果由于下溢发生范围错误,将返回正确结果(舍入后)。

错误处理

错误报告方式遵循 math_errhandling 中的规范。

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

  • 如果参数为 ±0,则原样返回。
  • 如果参数为 ±∞,则返回 NaN 并引发 FE_INVALID
  • 如果参数为 NaN,则返回 NaN。

注释

当参数为无穷大的情况在 C 语言(C++ 遵循其规范)中未被指定为定义域错误,但根据 POSIX 标准 被定义为定义域错误。

该函数在 π(1/2 + n) 处存在数学极点;然而没有任何常见的浮点数表示法能够精确表示π/2,因此不存在导致极点错误的参数值。

额外的重载不需要完全按照 (A) 的形式提供。只需确保对于整数类型的实参 num std :: tan ( num ) 具有与 std :: tan ( static_cast < double > ( num ) ) 相同的效果即可。

示例

#include <cerrno>
#include <cfenv>
#include <cmath>
#include <iostream>
// #pragma STDC FENV_ACCESS ON
const double pi = std::acos(-1); // 或 C++20 的 std::numbers::pi
int main()
{
    // 典型用法
    std::cout << "tan(1*pi/4) = " << std::tan(1*pi/4) << '\n' // 45°
              << "tan(3*pi/4) = " << std::tan(3*pi/4) << '\n' // 135°
              << "tan(5*pi/4) = " << std::tan(5*pi/4) << '\n' // -135°
              << "tan(7*pi/4) = " << std::tan(7*pi/4) << '\n'; // -45°
    // 特殊值
    std::cout << "tan(+0) = " << std::tan(0.0) << '\n'
              << "tan(-0) = " << std::tan(-0.0) << '\n';
    // 错误处理
    std::feclearexcept(FE_ALL_EXCEPT);
    std::cout << "tan(INFINITY) = " << std::tan(INFINITY) << '\n';
    if (std::fetestexcept(FE_INVALID))
        std::cout << "    FE_INVALID raised\n";
}

可能的输出:

tan(1*pi/4) = 1
tan(3*pi/4) = -1
tan(5*pi/4) = 1
tan(7*pi/4) = -1
tan(+0) = 0
tan(-0) = -0
tan(INFINITY) = -nan
    FE_INVALID raised

参阅

(C++11) (C++11)
计算正弦值 ( sin(x) )
(函数)
(C++11) (C++11)
计算余弦值 ( cos(x) )
(函数)
(C++11) (C++11)
计算反正切值 ( arctan(x) )
(函数)
计算复数的正切值 ( tan(z) )
(函数模板)
对 valarray 的每个元素应用函数 std::tan
(函数模板)
C 文档 关于 tan