C++ 中的 trunc()
函数将参数向零舍入,并返回小于或等于该参数的绝对值的最接近的整数值。
trunc() 原型 [截至 C++ 11 标准]
double trunc(double x); float trunc(float x); long double trunc(long double x); double trunc(T x); // For integral types
trunc() 函数接受一个参数,并返回 double、float 或 long double 类型的值。此函数定义在 <cmath> 标头文件中。
注意:要了解更多关于 C++ 中的 float 和 double,请访问 C++ float 和 double。
trunc() 参数
trunc() 函数接受一个参数,计算其截断值。
trunc() 返回值
trunc() 函数将 x 向零舍入,并返回小于或等于 x 的绝对值的最接近的整数值。
简单来说,trunc() 函数会截断小数点后的值,只返回整数部分。
示例 1:trunc() 在 C++ 中如何工作?
#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 函数返回相同的值。因此,在实际中它不常用于整数值。
另请阅读