In this C++ tutorial, you will learn how to round a given number to nearest integer value using round() function of cmath, with syntax and examples.
C++ round()
C++ round() returns integer value nearest to given value. Half-way (0.5) cases are rounded to higher nearest integer.
Syntax
The syntax of C++ round() is
round(x)
where
Parameter | Description |
---|---|
x | A double, float, long double, or IntegralType value. |
Returns
The return value depends on the type of value passed for parameter x. The return value of round(x) is
- double if x is double or IntegralType.
- float if x is float.
- long double if x is long double.
The synopsis of round() function is
float roundf(float); double round(double); long double roundl(long double);
round() is a function of cmath library. Include cmath library at the start of program, if using round() function.
Example
In this example, we read a double value from user into variable x, and find the nearest integer to this value in x, using round().
C++ Program
#include <iostream> #include<cmath> using namespace std; int main() { double x; cout << "Enter a number : "; cin >> x; double result = round(x); cout << "round(" << x << ") : " << result << endl; }
Output
Enter a number : 3.14 round(3.14) : 3 Program ended with exit code: 0
Enter a number : 3.5 round(3.5) : 4 Program ended with exit code:
Enter a number : 3.62 round(3.62) : 4 Program ended with exit code: 0
Conclusion
In this C++ Tutorial, we learned the syntax of C++ round(), and how to use this function to round off given number to nearest integer value, with the help of examples.