将float转换为double并返回float值在C ++中给出相同的值 [英] Does converting a float to a double and back to float give the same value in C++

查看:201
本文介绍了将float转换为double并返回float值在C ++中给出相同的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设在下面的代码中:

  float f1 = ...; 
double d1 = static_cast< double>(f1);
float f2 = static_cast< float>(d1);

ASSERT(f1 == f2);

变量 f1 被初始化为不是NaN。那么这个断言是否可以保证被C ++标准所保留?

这里有一些线索,但不是答案:


4.6浮点类型的前值可以转换为double类型的prvalue。价值不变。这种转换被称为浮点升级。
...

一个浮点类型的值可以转换为另一个浮点类型的值。如果源值可以在目标类型中精确表示,那么转换的结果是精确的
表示。如果源值位于两个相邻的目标值之间,则转换的结果是这些值中任何一个的实现定义选项。


Assume in the following code

float f1 = ...;
double d1 = static_cast<double>(f1);
float f2 = static_cast<float>(d1);

ASSERT( f1 == f2 );

the variable f1 is initialized to something which is not a NaN. Is the assertion then guaranteed to hold by the C++ standard?

解决方案

Here are some clues but not the answer:

4.6 A prvalue of type float can be converted to a prvalue of type double. The value is unchanged. This conversion is called floating point promotion. ...

4.8 A prvalue of floating point type can be converted to a prvalue of another floating point type. If the source value can be exactly represented in the destination type, the result of the conversion is that exact representation. If the source value is between two adjacent destination values, the result of the conversion is an implementation-defined choice of either of those values.

这篇关于将float转换为double并返回float值在C ++中给出相同的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆