Home » C++ programming language

trunc() function with example in C++

C++ trunc() function: Here, we are going to learn about the trunc() function with example of cmath header in C++ programming language?
Submitted by IncludeHelp, on April 27, 2019

C++ trunc() function

trunc() function is a library function of cmath header, it is used to round (truncate) the value toward zero, it accepts a number and returns the nearest integral value that is not the larger in magnitude than the given number.

Syntax of trunc() function:

    trunc(x);

Parameter(s): x – is the number to round toward zero.

Return value: double – it returns double type value that is the rounded (truncated) value of the number x.

Example:

    Input:
    float x = 2.3;    
    Function call:
    trunc(x);    
    Output:
    2

    Input:
    float x = 2.8;
    Function call:
    trunc(x);    
    Output:
    2

C++ code to demonstrate the example of trunc() function

// C++ code to demonstrate the example of 
// trunc() function

#include <iostream>
#include <cmath>
using namespace std;

// main() section
int main()
{
    float x;
    
    //input the number
    cout<<"Enter a float value: ";
    cin>>x;
    
    //rounding doward zero 
    cout<<"trunc("<<x<<"): "<<trunc(x);
    cout<<endl;

    return 0;
}

Output

First run:
Enter a float value: 2.3 
trunc(2.3): 2 

Second run:
Enter a float value: 2.5 
trunc(2.5): 2

Third run:
Enter a float value: 2.8 
trunc(2.8): 2 

Fourth run:
Enter a float value: -2.3
trunc(-2.3): -2 

Fifth run:
Enter a float value: -2.5
trunc(-2.5): -2

Sixth run:
Enter a float value: -2.8
trunc(-2.8): -2 


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.