C++舍入数字远离零

标签 c++ double rounding

您好,我想在 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/floorhttp://en.cppreference.com/w/cpp/numeric/math/floor

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

x = (x < 0) ? floor(x) : ceil(x);

关于C++舍入数字远离零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1326510/

相关文章:

python - 如何使用 Python Pulp 将主题限制为四舍五入整数

c++ - 如何执行注入(inject)到进程中的应用程序

java - 双重比较零特殊情况?

C++ 二维 vector 按列搜索

java - 小数格式和 double

c++ - 小数四舍五入为零

java - 如何在 Java 中保留 n 位小数

c 浮点向下舍入

android - android studio 项目中 CMake 和 NDK-build 的区别

c++ - 这是内存泄漏吗?试图重置类型类的类成员。 C++