英文:
Will int to double conversion round up, down or to nearest double?
问题
将整数转换为双精度浮点数时,它将始终向最接近的双精度浮点数(具有最小差值)进行四舍五入,而不会始终向上或向下四舍五入。
例如,对于static_cast<double>(100)
:
如果d2 < d1,它将向下四舍五入。
额外问题:是否可以通过特殊函数来强制处理器向下或向上四舍五入到最接近的双精度浮点数?据我所知,不幸的是,没有floor<double>
或ceil<double>
等函数。
英文:
Simple question: Will the conversion from an int, say 100, to a double "round" up or down to the next double or will it always round to the nearest one (smallest delta)?
e.g. for static_cast<double>(100)
:
Which way will it cast if d2 < d1?
Bonus question: Can I somehow force the processor to "round" down or up to the closes double using special functions? As I see it, there's no floor<double>
or ceil<double>
unfortunately.
答案1
得分: 14
请注意,一个32位的int
可以被64位的IEEE 754 double
精确表示(实际上可以精确表示高达53位的整数)。
如果您使用的整数大于您的浮点类型可以表示的范围,那么适用于实浮点整数转换的规则如下:
- 如果该值可以表示,但无法精确表示,则结果是最接近的较高或较低值(换句话说,舍入方向是实现定义的),尽管如果支持IEEE算术,则舍入到最近。在这种情况下,未指定是否引发FE_INEXACT。
- 如果该值无法表示,行为未定义,尽管如果支持IEEE算术,FE_INVALID会被触发,并且结果值是未指定的。
没有C++标准函数来控制舍入模式,大多数实现将使用IEEE最近舍入。
英文:
Note that a 32-bit int
can be represented exactly by a 64-bit IEEE 754 double
(it can actually represent up to 53-bit integers precisely).
If you're using an integer that is larger than can be represented by your floating point type then the rules at Real floating-integer conversions apply:
> * if the value can be represented, but cannot be represented exactly, the result is the nearest higher or the nearest lower value (in other words, rounding direction is implementation-defined), although if IEEE arithmetic is supported, rounding is to nearest. It is unspecified whether FE_INEXACT is raised in this case.
> * if the value cannot be represented, the behavior is undefined, although if IEEE arithmetic is supported, FE_INVALID is raised and the result value is unspecified.
There is no c++ standard function to control the rounding mode, most implementations will use the IEEE round to nearest.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论