跳到主要内容

Trunc

定义于头文件 <cmath> 中。

描述

计算不大于 num 的最近整数。⏳ 库为所有 cv 非限定浮点类型提供了 std::trunc 的重载作为参数 num 的类型  (自 C++23 起)

⏳为所有整型提供了额外重载,它们被视为 double

声明

// 1)
constexpr /* floating-point-type */ trunc( /* floating-point-type */ num );
// 2)
constexpr float truncf( float num );
// 3)
constexpr long double truncl( long double num );
附加重载
// 4)
template< class Integer >
constexpr double trunc ( Integer num );

参数

num - 浮点或整数值

返回值

如果没有发生错误,则返回不大于 num 的最近整数值(换句话说,num 向零舍入)。

错误处理

错误按 math_errhandling 中指定的方式报告。

如果实现支持 IEEE 浮点运算(IEC 60559

当前的舍入模式无效。
如果 num±∞,则返回,不修改
如果 num±0,则返回,不修改
如果 num 是 NaN,则返回 NaN

备注

截断非整数有限值时,可能会(但不是必须)引发 FE_INEXACT。

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

从浮点类型到整型的隐式转换也会向零舍入,但仅限于目标类型可以表示的值。

额外的重载不需要完全按照额外重载提供。它们只需要足以确保对于其整数类型的参数 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

Trunc

定义于头文件 <cmath> 中。

描述

计算不大于 num 的最近整数。⏳ 库为所有 cv 非限定浮点类型提供了 std::trunc 的重载作为参数 num 的类型  (自 C++23 起)

⏳为所有整型提供了额外重载,它们被视为 double

声明

// 1)
constexpr /* floating-point-type */ trunc( /* floating-point-type */ num );
// 2)
constexpr float truncf( float num );
// 3)
constexpr long double truncl( long double num );
附加重载
// 4)
template< class Integer >
constexpr double trunc ( Integer num );

参数

num - 浮点或整数值

返回值

如果没有发生错误,则返回不大于 num 的最近整数值(换句话说,num 向零舍入)。

错误处理

错误按 math_errhandling 中指定的方式报告。

如果实现支持 IEEE 浮点运算(IEC 60559

当前的舍入模式无效。
如果 num±∞,则返回,不修改
如果 num±0,则返回,不修改
如果 num 是 NaN,则返回 NaN

备注

截断非整数有限值时,可能会(但不是必须)引发 FE_INEXACT。

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

从浮点类型到整型的隐式转换也会向零舍入,但仅限于目标类型可以表示的值。

额外的重载不需要完全按照额外重载提供。它们只需要足以确保对于其整数类型的参数 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