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

C如何正确地将const float舍入为unsigned int

发布时间:2020-12-16 09:55:12 所属栏目:百科 来源:网络整理
导读:所以我有一个const浮点数,范围从0.0到1.0.通过舍入或截断将这个转换为unsigned int的正确方法是什么? 这可以接受吗? const float f=0.5f;unsigned int i=static_castunsigned int(f); 解决方法 是的,如果您想要截断,那么这是完全可以接受的,如果您不关心负
所以我有一个const浮点数,范围从0.0到1.0.通过舍入或截断将这个转换为unsigned int的正确方法是什么?

这可以接受吗?

const float f=0.5f;
unsigned int i=static_cast<unsigned int>(f);

解决方法

是的,如果您想要截断,那么这是完全可以接受的,如果您不关心负数或溢出会发生什么.

如果你想要舍入,首先调用roundf(或者,如果你想要一个不同的舍入规则而不是“从零开始的一半舍入”,请编写你自己的代码).

如果您想处理负数或溢出,则需要在转换前进行检查.

根据标准中的5.2.9,在这种情况下,static_cast被定义为给出与unsigned int i(f)相同的值.我认为大多数样式指南都会同意static_cast是首选的(因为使得强制转换显而易见并且通常是一件好事).

更详细:

根据4.9.1:

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

我不确定const-away究竟是如何在C 14中运行的,但我认为它不是一个限定转换,而是4.1.1中左值到右值转换的一部分:

A glvalue (3.10) of a non-function,non-array type T can be converted to a prvalue …?If T is a non-class type,the type of the prvalue is the cv-unqualified version of T.

因此,f有一个左值到右值的左值转换,从左值浮点数浮点数到另一个浮点值,然后是从浮点数到浮点数的一个浮点积分转换,所以4.0.1它是一个标准转换,所以5.2.9它是有效的的static_cast.

(编辑:李大同)

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

    推荐文章
      热点阅读