加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

没有未定义的行为,哪些浮点值无法转换为int [c]?

发布时间:2020-12-16 03:25:50 所属栏目:百科 来源:网络整理
导读:我刚刚从C 14标准(我的重点)中读到了这个: 4.9 Floating-integral conversions [conv.fpint] 1 A prvalue of a floating point type can be converted to a prvalue of an integer type. The conversion truncates; that is,the fractional part is discard
我刚刚从C 14标准(我的重点)中读到了这个:

4.9 Floating-integral conversions [conv.fpint]

1 A prvalue of a floating point type can be converted to a prvalue of an integer type. The conversion truncates; that is,the fractional part is discarded. The behavior is undefined if the truncated value cannot be
represented in the destination type.
[…]

这让我思考

>截断后哪个浮点值不能表示为int? (这取决于实施吗?)
>如果有,这是否意味着auto x = static_cast< int>(float)是不安全的?
>将float转换为int的正确/安全方法是什么(假设你想要截断)?

解决方法

浮点数值超出int范围应该不足为奇.发明了浮点值以充分表示非常大(也非常小)的值.

> INT_MAX 1(通常等于2147483648)不能用int表示,但可以用float表示.
>是的,static_cast< int>(float)与未定义的行为一样不安全.然而,对于足够大的整数x和y而言,像x y这样简单的东西也是UB,所以这里也没有什么大惊喜.
>正确的做法取决于应用程序,就像在C中一样. Boost有numeric_cast,它会在溢出时抛出异常;这可能对你有好处.要做饱和度(将太大的值转换为INT_MIN和INT_MAX),写一些这样的代码

float f;
int i;
...
if (static_cast<double>(INT_MIN) <= f && f < static_cast<double>(INT_MAX))
    i = static_cast<int>(f);
else if (f < 0)
    i = INT_MIN;
else
    i = INT_MAX;

但是,这并不理想.您的系统是否具有可以表示int的最大值的double类型?如果是的话,它会起作用.另外,您想要如何舍入接近最小值或最大值int的值?如果您不想考虑这些问题,请使用boost :: numeric_cast,如here所述.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读