C ++:如何将一个double转换为一个int? [英] C++: How to round a double to an int?

查看:3458
本文介绍了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 <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 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.有关说明,请参阅 stackoverflow答案(或简单地搜索IEEE 754浮点)。

A follow up question might be why the float isn't stored as exactly 55. For an explanation, see this stackoverflow answer (or simply search IEEE 754 floating point).

这篇关于C ++:如何将一个double转换为一个int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆