Round in STL C++

C++ STL Function : round()

On this page we will discuss about library function round() in STL which is used in C++. The cmath header file is a C++ standard library header file that contains a set of math functions and macro definitions that are used to perform mathematical operations. The round function in C++ is a function in the cmath library that rounds a number to the nearest integer.

Round in STL C++

Library Function round() in C++

In C++ programming language the round() function is included in cmath header file.

The round() function in C++ can be used to round any floating-point number within the range of the corresponding floating-point type (double, float, or long double) to the nearest integer. The value is rounded to the nearest integer, with half-integers being rounded to the nearest even integer.
For example, round(1.5) will return 2, while round(2.5) will return 2.

Syntax

double round(double x);
float round(float x);
long double round(long double x);

Parameters

The round() function takes a single parameter x.

ParameterDescription
xIt is a floating-point number which is to be rounded off.

Return value

The round() function in C++ returns the nearest integer to the floating-point number passed as an parameter as a double, float, or long double depending on the type of the function being called.

Implementation of round() function in C++

Example 1:

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

int main() {
    
  double num = 3.14;
  cout << "round(" << num  << ") = "<< round(num) << endl;  

  num = 3.7;
  cout << "round(" << num  << ") = "<< round(num) << endl; 

  return 0;
}

Output:

round(3.14) = 3
round(3.7) = 4

Example 2:

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

int main() {

  double num, result;

  num = -13.13;
  result = round(num);

  cout << "round(" << num << ") = " << result << endl;

  num = -15.48;
  result = round(num);

  cout << "round(" << num << ") = " << result << endl;
    
  num = -60.7;
  result = round(num);

  cout << "round(" << num << ") = " << result;
      
  return 0;
}

Output:

round(-13.13) = -13
round(-15.48) = -15
round(-60.7) = -61

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription