跳到主要内容

C++ trunc() 截断函数

C++ 中的 trunc() 函数将参数向零取整,返回不大于该参数的最近整数值。

trunc() 函数原型 [C++ 11 标准起]

double trunc(double x);
float trunc(float x);
long double trunc(long double x);
double trunc(T x); // 对于整数类型

trunc() 函数接受单个参数,并返回 double、float 或 long double 类型的值。这个函数定义在 <cmath> 头文件中。

trunc() 参数

trunc() 函数接受一个参数,计算其截断值。

trunc() 返回值

trunc() 函数将 x 向零取整,返回不大于 x 的最近整数值。

简单来说,trunc() 函数截断小数点后的值,只返回整数部分。

示例 1:C++ 中 trunc() 的工作原理

#include <iostream>
#include <cmath>

using namespace std;

int main()
{
double x = 10.25, result;
result = trunc(x);
cout << "trunc(" << x << ") = " << result << endl;

x = -34.251;
result = trunc(x);
cout << "trunc(" << x << ") = " << result << endl;

return 0;
}

当你运行程序时,输出将会是:

trunc(10.25) = 10
trunc(-34.251) = -34

示例 2:对整数类型使用 trunc() 函数

#include <iostream>
#include <cmath>

using namespace std;

int main()
{
int x = 15;
double result;
result = trunc(x);
cout << "trunc(" << x << ") = " << result << endl;

return 0;
}

当你运行程序时,输出将会是:

trunc(15) = 15

对于整数值,应用 trunc 函数返回的结果与原值相同。因此,在实际中不常对整数值使用此函数。