c ++从零开始舍入数字

Emr*_*mre 7 c++ double rounding

嗨我想在C++中将这样的双数字(远离零)舍入:

  4.2 ---->   5
  5.7 ---->   6
 -7.8 ---->  -8
-34.2 ----> -35
Run Code Online (Sandbox Code Playgroud)

有效的方法是什么?

Rub*_*ink 25

inline double myround(double x)
{
  return x < 0 ? floor(x) : ceil(x);
}
Run Code Online (Sandbox Code Playgroud)

正如Huppie引用的文章中所提到的,这最好表示为适用于所有浮点类型的模板

http://en.cppreference.com/w/cpp/numeric/math/floorhttp://en.cppreference.com/w/cpp/numeric/math/floor

或者,感谢Pax,一个非功能版本:

x = (x < 0) ? floor(x) : ceil(x);
Run Code Online (Sandbox Code Playgroud)