How to Round Numbers in C++

In C++, you can implement a rounding function using the following methods:

#include <iostream>
#include <cmath>

double round(double num) {
    return floor(num + 0.5);
}

int main() {
    double num = 3.14159;
    double rounded_num = round(num);

    std::cout << "Original number: " << num << std::endl;
    std::cout << "Rounded number: " << rounded_num << std::endl;

    return 0;
}

In the example above, we defined a function called round to implement rounding off. In the main function, we called this function and displayed the result. You can pass the number you want to round off as a parameter to the round function and store the result in another variable for further operations.

bannerAds