您可以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支持.
例如:
#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)
int nearest = 5;
int result = (input+nearest/2)/nearest*nearest;
Run Code Online (Sandbox Code Playgroud)