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 variables
double x = 15.6;
double result;
// implementing the trunc() function
result = trunc(x);
cout << "trunc(" << x << ") = " << result << endl;
return 0;
}

Code explanation

  • Lines 9-10: We create variables x and result.

  • Line 13: We implement the trunc() function on x and assign the value to the result variable.

  • Line 14: We print the result variable.

Free Resources