Selected Reading

C++ cmath round() Function



The C++ cmath round() function is used to round a number to the nearest whole number (integer). If the decimal part of the number is 0.5 or greater, it rounds it up to the next whole number; if it is less than 0.5, it rounds it down to the nearest lower whole number. Rounding numbers helps present data more clearly and meet specific formatting requirements.

Syntax

Following is the syntax for C++ cmath round() function.

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

Parameters

  • x - The value to be rounded to the nearest integer.

Return Value

The value of x rounded to the nearest integral (as a floating-point value).

Time Complexity

The time complexity of this function is constant, i.e.,O(1).

Example 1

Let's see the basic rounding of a floating point number x using the round() function.

#include <iostream>
#include <cmath>
int main() {
   double value = 4.7;
   std::cout << "Rounded value of 4.7: " << std::round(value) << std::endl;
   return 0;
}

Output

Output of the above code is as follows

Rounded value of 4.7: 5

Example 2

This example demonstrates how std::round() manages float accuracy by rounding values to the nearest integer based on their fractional parts.

#include <iostream>
#include <cmath>
int main() {
   float value = 7.499f;
   std::cout << "Rounded value of 7.499: " << std::round(value) << std::endl;
   return 0;
}

Output

Following is the output of the above code

Rounded value of 7.499: 7

Example 3

The following example demonstrates how the round() function handles values at 0.5, highlighting its behaviour with mid-point values.

#include <iostream>
#include <cmath>
int main() {
   double x = 3.5;
   double result = round(x);
   std::cout << "round(3.5) = " << result << std::endl;
   x = -1.5;
   result = round(x);
   std::cout << "round(-1.5) = " << result << std::endl;
   return 0;
}

Output

If we run the above code it will generate the following output

round(3.5) = 4
round(-1.5) = -2
cpp_cmath.htm
Advertisements