您好,我想在 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);
关于C++舍入数字远离零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1326510/