Namespaces
Variants

std:: trunc, std:: truncf, std:: truncl

From cppreference.net
Common mathematical functions
Nearest integer floating point operations
trunc
(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 trunc ( float num ) ;

double trunc ( double num ) ;

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

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

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

目录

参数

num - 浮点数或整数值

返回值

如果没有发生错误,将返回不大于 num 绝对值的最近整数值(换言之, num 向零舍入后的值)。

返回值
math-trunc.svg
num

错误处理

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

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

  • 当前的 舍入模式 无效。
  • num 为 ±∞,则直接返回该值。
  • num 为 ±0,则直接返回该值。
  • num 为 NaN,则返回 NaN。

注释

FE_INEXACT 在截断非整数有限值时可能(但非必须)被引发。

在所有标准浮点格式中,最大可表示的浮点值都是精确整数,因此该函数本身永远不会溢出;然而当结果存储在整数变量中时,可能会溢出任何整数类型(包括 std::intmax_t )。

从浮点类型到整数类型的 隐式转换 同样会向零舍入,但仅限于目标类型能够表示的数值范围。

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

示例

#include <cmath>
#include <initializer_list>
#include <iostream>
int main()
{
    const auto data = std::initializer_list<double>
    {
        +2.7, -2.9, +0.7, -0.9, +0.0, 0.0, -INFINITY, +INFINITY, -NAN, +NAN
    };
    std::cout << std::showpos;
    for (double const x : data)
        std::cout << "trunc(" << x << ") == " << std::trunc(x) << '\n';
}

可能的输出:

trunc(+2.7) == +2
trunc(-2.9) == -2
trunc(+0.7) == +0
trunc(-0.9) == -0
trunc(+0) == +0
trunc(+0) == +0
trunc(-inf) == -inf
trunc(+inf) == +inf
trunc(-nan) == -nan
trunc(+nan) == +nan

参见

(C++11) (C++11)
不大于给定值的最近整数
(函数)
(C++11) (C++11)
不小于给定值的最近整数
(函数)
(C++11) (C++11) (C++11) (C++11) (C++11) (C++11) (C++11) (C++11) (C++11)
最近整数(中间值向远离零方向舍入)
(函数)
C 文档 for trunc