📅  最后修改于: 2023-12-03 15:29:51.621000             🧑  作者: Mango
The trunc()
function in C++ is used to truncate a floating-point value to its nearest integer towards zero. It takes one argument, which is the floating-point value to be truncated.
Here's the syntax of the trunc()
function:
double trunc(double x);
The argument x
is the floating-point value to be truncated. The function returns the truncated value as a double.
For example, if we have the floating-point value 3.8
, trunc(3.8)
will return 3.0
. If we have the floating-point value -3.8
, trunc(-3.8)
will return -3.0
.
Here's an example program that uses trunc()
:
#include <iostream>
#include <cmath>
int main() {
double x = 3.8;
std::cout << "Truncate " << x << " to " << trunc(x) << std::endl;
x = -3.8;
std::cout << "Truncate " << x << " to " << trunc(x) << std::endl;
return 0;
}
In this program, we include the <cmath>
header to use the trunc()
function. We then declare a double variable x
and assign it the value 3.8
. We use trunc(x)
to truncate x
to the nearest integer towards zero and output the result using std::cout
. We then repeat the process for the value -3.8
.
When we run this program, we get the following output:
Truncate 3.8 to 3
Truncate -3.8 to -3
As we can see, the trunc()
function effectively truncates floating-point values to their nearest integer towards zero.