使用Boost在C++中舍入到最接近的数字?

twe*_*ypi 6 c++ math boost rounding

有没有办法在Boost库中舍入到最接近的数字?我的意思是任何数字,2个,5个,17个等等等等.

或者还有另一种方法吗?

Ben*_*ier 5

您可以lround在C99中使用.

#include <cmath>
#include <iostream>

int main() {
  cout << lround(1.4) << "\n";
  cout << lround(1.5) << "\n";
  cout << lround(1.6) << "\n";
}
Run Code Online (Sandbox Code Playgroud)

(输出1,2,2).

检查编译器文档是否和/或如何启用C99支持.


Evg*_*yuk 5

增强舍入函数

例如:

#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;
}
Run Code Online (Sandbox Code Playgroud)

输出是:

0
0
1
1
0
-1
-1
Run Code Online (Sandbox Code Playgroud)


For*_*ght 3

int nearest = 5;
int result = (input+nearest/2)/nearest*nearest;
Run Code Online (Sandbox Code Playgroud)