C++ round()
Published Oct 24, 2022Updated Dec 21, 2022
The round() function returns the integer that is closest to the argument, with halfway cases rounded away from the ending zero.
Syntax
round(num);
- The
numparameter must be adouble,float, orlong double. - The return value will be an integer.
- If the decimal in
numis0.5or higher, the closest integer greater thannumis returned.
Example
The following example showcases the round() function being applied to two double values, one of which is a halfway case:
#include <iostream>#include <cmath>int main() {double num1 = 9.23;double result1;result1 = std::round(num1);std::cout << "The result of round(9.23) is " << result1 << "\n";double num2 = 4.5;double result2;result2 = std::round(num2);std::cout << "The result of round(4.5) is " << result2 << "\n";}
This produces the following output:
The result of round(9.23) is 9The result of round(4.5) is 5
Codebyte Example
The following example is runnable and rounds the halfway case away from zero:
Learn C++ on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn C++ — a versatile programming language that’s important for developing software, games, databases, and more.
- Beginner Friendly.11 hours