Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 326
meds Avatar asked Jul 18 '10 08:07

meds


2 Answers

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.

like image 188
Benjamin Bannier Avatar answered Oct 04 '22 08:10

Benjamin Bannier


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
like image 24
Evgeny Panasyuk Avatar answered Oct 04 '22 08:10

Evgeny Panasyuk