round() function in C++
In this tutorial, we will learn about the round() function in C++. This function is defined in cmath header in C++. We will be using it in our C++ program to round a given number with halfway cases rounded away from zero.
The syntax for the round() function is as follows:
round(number);
The return type for this function is the same as the type of input parameter. i. e. number in the above syntax. It can be double, float, long double etc.
Examples of C++ round() function:
round() function in C++ rounds a number to the nearest integral value. Here are a few examples that illustrates the working of this function. I will show you multiple examples of this function in the same program.
Suppose the input number is 45.8. If we pass this number as input in round() function, it returns 49.
round(45.8) = 49.
Similarly,
round(34.4) = 34.
Let us implement it in a C++ program. This will clear all the doubts.
#include <iostream> #include <cmath> using namespace std; int main() { cout << round(-0.9) << endl; cout << round(-0.7) << endl; cout << round(-0.5) << endl; cout << round(-0.3) << endl; cout << round(-0.1) << endl; cout << round(0.2) << endl; cout << round(0.4) << endl; cout << round(0.6) << endl; cout << round(0.8) << endl; return 0; }
The above program gives the below output:
-1 -1 -1 -0 -0 0 0 1 1
As you can observe from the above example round() function works very well to round the floating-point numbers. This function can be used in C++ in many applications.
Thank you.
Also, read: C++ program to round off numbers nearest 10
Leave a Reply