[英]Rounding to nearest number in C++ using Boost?
有没有办法在Boost库中舍入到最接近的数字? 我的意思是任何数字,2个,5个,17个等等等等。
或者还有另一种方法吗?
您可以使用C99中的lround
。
#include <cmath>
#include <iostream>
int main() {
cout << lround(1.4) << "\n";
cout << lround(1.5) << "\n";
cout << lround(1.6) << "\n";
}
(输出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;
}
输出是:
0
0
1
1
0
-1
-1
int nearest = 5;
int result = (input+nearest/2)/nearest*nearest;
实际上你根本不需要Boost,只需要C ++库中包含的C库。 具体来说,您需要包含cmath标头:
汇总一个数字:ceil(): http ://www.cplusplus.com/reference/clibrary/cmath/ceil/
向下舍入一个数字:floor(): http : //www.cplusplus.com/reference/clibrary/cmath/floor/
您可以编写自己的循环函数:
#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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.