C++:如何将 double 舍入为 int?

C++: How to round a double to an int?(C++:如何将 double 舍入为 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)