嗨,我想在C ++中四舍五入像这样的双数(远离零):
4.2 ----> 5
5.7 ----> 6
-7.8 ----> -8
-34.2 ----> -35
执行此操作的有效方法是什么?
inline double myround(double x)
{
return x < 0 ? floor(x) : ceil(x);
}
如the article Huppie cites中所述,最好将其表示为适用于所有浮点类型的模板
请参见http://en.cppreference.com/w/cpp/numeric/math/floor和http://en.cppreference.com/w/cpp/numeric/math/floor
或者,由于Pax,非功能版本:
x = (x < 0) ? floor(x) : ceil(x);
[关于CPlusPlus.com的类似问题,有一篇不错的文章。解决您的问题的简单方法应该是这样:
double customRound( double value ) const {
return value < 0 ? floor( value ) : ceil( value );
}
一种更好的解决方案是本文中提到的使用模板的解决方案:
//--------------------------------------------------------------------------
// symmetric round up
// Bias: away from zero
template <typename FloatType>
FloatType ceil0( const FloatType& value )
{
FloatType result = std::ceil( std::fabs( value ) );
return (value < 0.0) ? -result : result;
}
尝试
double rounded = _copysign(ceil(abs(x)), x);
这将起作用,甚至不需要math.h
或任何库。我采用了一种独特的方法来实现所需的功能。地板负数和天花板正数只是做到这一点的一种方法。它的作用与截断数字并将绝对值加1相同,If它是not now整数。像这样:
inline double InvertedTrunc(double Number) {
return (Number == (long long int)Number ? Number : ((long long int)Number)+(Number < 0 ? -1 : 1)); //casting to int truncates it
}