C ++:如何将一个double转换为一个int?
可能重复:
round()for C ++
因此,当我做
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
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 is now 55.499999...
int y = (int)x; // truncated to 55
C ++ 11还引入了 std :: round ,这可能使用类似的逻辑,将| 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.
后续问题可能是为什么 float不是存储为55.有关说明,请参阅此 *答案(或简单地搜索IEEE 754浮点)。
A follow up question might be why the float isn't stored as exactly 55. For an explanation, see this * answer (or simply search IEEE 754 floating point).