简体   繁体   中英

Rounding to nearest number in C++ using Boost?

Is there a way to round to the nearest number in the Boost library? I mean any number, 2's, 5's, 17's and so on and so forth.

Or is there another way to do it?

You can use lround available in C99.

#include <cmath>
#include <iostream>

int main() {
  cout << lround(1.4) << "\n";
  cout << lround(1.5) << "\n";
  cout << lround(1.6) << "\n";
}

(outputs 1, 2, 2).

Check your compiler documentation if and/or how you need to enable C99 support.

Boost Rounding Functions

For example:

#include <boost/math/special_functions/round.hpp>
#include <iostream>
#include <ostream>
using namespace std;

int main()
{
    using boost::math::lround;
    cout << lround(0.0) << endl;
    cout << lround(0.4) << endl;
    cout << lround(0.5) << endl;
    cout << lround(0.6) << endl;
    cout << lround(-0.4) << endl;
    cout << lround(-0.5) << endl;
    cout << lround(-0.6) << endl;
}

Output is:

0
0
1
1
0
-1
-1
int nearest = 5;
int result = (input+nearest/2)/nearest*nearest;

You actually don't need Boost at all, just the C library included in the C++ library. Specifically, you need to include the cmath header:

Round up a number: ceil(): http://www.cplusplus.com/reference/clibrary/cmath/ceil/

Round down a number: floor(): http://www.cplusplus.com/reference/clibrary/cmath/floor/

You can write your own round function then:

#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <string>
#include <utility>

double roundFloat(double x)
{
    double base = floor( x );

    if ( x > ( base + 0.5 ) )
            return ceil( x );
    else    return base;
}

int main()
{
    std::string strInput;
    double input;

    printf( "Type a number: " );
    std::getline( std::cin, strInput );
    input = std::atof( strInput.c_str() );

    printf( "\nRounded value is: %7.2f\n", roundFloat( input ) );

    return EXIT_SUCCESS;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM