The round()
function in C++ is used to round off a number to the nearest integer.
To use the round()
function, include either of the following libraries:
#include <cmath>
Or:
#include <ctgmath>
The round()
function can be declared as:
double round( double num )
Or:
float round( float num )
Or:
long double round( long double num )
Or:
double round ( T num )
num
: The number to be rounded off.The round()
function returns the nearest integer of the number num
.
Note: The
round()
function rounds a number to the nearest integer, regardless of the currentround
mode.
Consider the code snippet below, which demonstrates the use of the round()
function:
#include <cmath>#include <iostream>using namespace std;int main(){double num1 = 1.24;double num2 = 1.5;double num3 = 1.78;double rounded1 = round(num1);cout<<"round( "<<num1<<" ) = "<<rounded1<<endl;double rounded2 = round(num2);cout<<"round( "<<num2<<" ) = "<<rounded2<<endl;double rounded3 = round(num3);cout<<"round( "<<num3<<" ) = "<<rounded3<<endl;return 0;}
Three variables, num1
, num2
, and num3
, are declared in lines 6-8. The round()
function is used in line 10, line 13, and line 16 to find the nearest integer for num1
, num2
, and num3
, respectively.
Free Resources