What is the trunc() method in C++?
Overview
The trunc() function in C++ is used to round a given argument x towards 0 and return the nearest integer value that is not greater than x in magnitude.
Syntax
double trunc(double x);
float trunc(float x);
long double trunc(long double x);
Parameters
The trunc() function takes a single parameter value, x, that represents the value whose truncated value is to be computed.
Return value
The trunc() function returns the nearest integer value to x that is not greater than x.
Code example
#include <iostream>#include <cmath>using namespace std;int main(){// creating variablesdouble x = 15.6;double result;// implementing the trunc() functionresult = trunc(x);cout << "trunc(" << x << ") = " << result << endl;return 0;}
Code explanation
-
Lines 9-10: We create variables
xandresult. -
Line 13: We implement the
trunc()function onxand assign the value to theresultvariable. -
Line 14: We print the
resultvariable.