Round a number to the nearest integer in C++

In this tutorial, We are going to learn about How to round off a number to the nearest integer in C++. The data types used  for rounding off the integer can be are as follows:

  • float
  • double
  • long double

Let us consider some examples to have a better understanding of the problem.

For Example:
If the input is 
float a = 37.55555

so now the output will become 

result= 38
 

So to solve this problem we can use we can simply use a C++ STL round Function. For a detailed study about this function follow this link round() function in C++

Implementation of the Problem of rounding a number to the nearest integer

#include<iostream>
#include <cmath>
using namespace std;
//Driver program
int main()
{
float number ;//float datatype input 
double num1;// double datatype input 
long double num2;// long double datatype input 

cout<<" Enter the number ";
cin>>number >> num1 >> num2 ;

//printing all the rounded off number's using the C++  round STL Function 
cout<<" Rounded number "<<" " << round(number)<< " "<< round(num1)<<" "<< round(num2);

return 0;

}

 

OUTPUT

Enter the number 12.22
13.4559
12.19
Rounded number 12 13 12
                                  

 

Round For Long Integer and Long Long Integer in C++

For rounding off of the long integer and long long integer data types we must use two more C++ STL functions which are as follows :

  • llround() – For long long integer data type(Ranges from -2,147,483,648 to 2,147,483,647)
  • lround() – For long integer data type(Ranges from -(2^63) to (2^63))

Below are some implementations for the following in a C++ Program

 

#include <cmath>
#include <iostream>
using namespace std;
  
// Driver program
int main()
{ 
    //Below are some examples .

    // For lround
    cout << lround(-0.0) << "\n";
    cout << lround(2.3) << "\n";


    // For llround
    cout <<  llround(-0.01234) << "\n";
    cout <<  llround(2.3563) << "\n";

   return 0;
}

 

OUTPUT :

0
2
0
2

Leave a Reply

Your email address will not be published.