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

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.