English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

C++ trunc() function usage and examples

C++ Library Function <cmath>

C ++The trunc() function in the parameter rounds to zero and returns the closest integer value whose magnitude is not greater than the parameter.

trunc() prototype [from C ++ 11[Standard]

double trunc(double x);
float trunc(float x);
long double trunc(long double x);
double trunc(T x); //integer type

The trunc() function takes a single parameter and returns a value of type double, float, or long double. This function is in<cmath>defined in the header file.

trunc() parameter

The trunc() function takes a single parameter, whose trunc value will be calculated.

trunc() return value

The trunc() function rounds x to zero and returns the closest integer value whose magnitude is not greater than x.

In short, the trunc() function truncates the decimal part and returns only the integer part.

Example1: How does trunc() work in C ++working in 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;
}

When the program is executed, the output is:

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

Example2: The trunc() function of integer type

#include <iostream>
#include <cmath>
using namespace std;
int main()
{
    int x = 15;
    double result;
    result = trunc(x);
    cout << "trunc(" << x << ") = " << result << endl;
    return 0;
}

When the program is executed, the output is:

trunc(15) = 15

For integer values, the trunc function will return the same result. Therefore, it is not commonly used to represent integer values in practice.

C++ Library Function <cmath>