C++: How to round a double to an int?(C++:如何将 double 舍入为 int?)
问题描述
我有一个 double(称为 x),本来是 55,但实际上存储为 54.999999999999943157,这是我刚刚意识到的.
I have a double (call it x), meant to be 55 but in actuality stored as 54.999999999999943157 which I just realised.
所以当我这样做时
double x = 54.999999999999943157;
int y = (int) x;
y = 54 而不是 55!
y = 54 instead of 55!
这让我困惑了很久.我怎样才能让它正确地四舍五入?
This puzzled me for a long time. How do I get it to correctly round?
推荐答案
在转换前加 0.5(如果 x > 0)或减去 0.5(如果 x <0),因为编译器总是会截断.
add 0.5 before casting (if x > 0) or subtract 0.5 (if x < 0), because the compiler will always truncate.
float x = 55; // stored as 54.999999...
x = x + 0.5 - (x<0); // x is now 55.499999...
int y = (int)x; // truncated to 55
C++11 还引入了 std::round,它可能使用类似的逻辑,将 0.5 添加到 |x|在引擎盖下(如果有兴趣,请参阅链接),但显然更强大.
C++11 also introduces std::round, which likely uses a similar logic of adding 0.5 to |x| under the hood (see the link if interested) but is obviously more robust.
后续问题可能是为什么浮点数没有准确存储为 55.有关说明,请参阅 this stackoverflow 答案.
A follow up question might be why the float isn't stored as exactly 55. For an explanation, see this stackoverflow answer.
这篇关于C++:如何将 double 舍入为 int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++:如何将 double 舍入为 int?


- 如何提取 __VA_ARGS__? 2022-01-01
- 从父 CMakeLists.txt 覆盖 CMake 中的默认选项(...)值 2021-01-01
- OpenGL 对象的 RAII 包装器 2021-01-01
- 将函数的返回值分配给引用 C++? 2022-01-01
- XML Schema 到 C++ 类 2022-01-01
- 使用 __stdcall & 调用 DLLVS2013 中的 GetProcAddress() 2021-01-01
- GDB 不显示函数名 2022-01-01
- 将 hdc 内容复制到位图 2022-09-04
- DoEvents 等效于 C++? 2021-01-01
- 哪个更快:if (bool) 或 if(int)? 2022-01-01