int到double的转换会将整数向最接近的双精度数四舍五入。

huangapple go评论102阅读模式
英文:

Will int to double conversion round up, down or to nearest double?

问题

将整数转换为双精度浮点数时,它将始终向最接近的双精度浮点数(具有最小差值)进行四舍五入,而不会始终向上或向下四舍五入。

例如,对于static_cast<double>(100)

int到double的转换会将整数向最接近的双精度数四舍五入。

如果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&lt;double&gt;(100):

int到double的转换会将整数向最接近的双精度数四舍五入。

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&lt;double&gt; or ceil&lt;double&gt; 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.

huangapple
  • 本文由 发表于 2023年3月8日 15:46:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/75670439.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定