嗨我想在C ++中将这样的双数字(远离零)舍入:
4.2 ----> 5
5.7 ----> 6
-7.8 ----> -8
-34.2 ----> -35
这样做的有效方法是什么?
答案 0 :(得分:25)
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);
答案 1 :(得分:2)
关于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;
}
答案 2 :(得分:1)
Ruben Bartelink的x < 0 ? floor(x) : ceil(x);
方法是好的。但是请考虑使用x = -0.0
,x = NaN
的特殊情况会发生什么情况。
请考虑以下内容,而不是让myround(-0.0)
可能返回+0.0
1 并让myround(NaN)
返回有效负载NaN
的情况。
myround_alt(-0.0)
返回-0.0
。
myround_alt(NaN)
更有可能返回不变的有效载荷NaN。数量不多的东西很棘手,而且定义不明确。 IAC,它是我正在寻找的myround_alt(-0.0)
-> -0.0
。
inline double myround_alt(double x) {
if (x > 0) return ceil(x);
if (x < 0) return floor(x);
return x;
}
1 IEC 60559 floating-point arithmetic指定ceil(±0)
返回±0
,因此严格遵循该规范的实现不需要这种方法。然而,许多C浮点实现并没有遵循该要求(C并不需要),或者在这种情况下失败了。
答案 3 :(得分:-1)
试
double rounded = _copysign(ceil(abs(x)), x);