背景:我在记录中有一些元素,其中某些元素可以是float,unsigned int或unsigned long long。因此,尽管我使用float作为公共值从读取这些元素的函数中返回。
但是,我在从unsigned int转换为float时看到了这个奇怪的错误。在打印值时,它会更改。我该如何避免呢?我不应该从该函数返回float吗?
#include <iostream>
#include <limits>
using namespace std;
int main()
{
unsigned int myU = numeric_limits<unsigned int>::max();
cout<<" myU is "<<myU<<'\n'; //correct
float myF = (float) myU;
cout<<" back To Long "<<(unsigned long long ) myF<<'\n'; //error?
cout<<" back To unsigned int "<<(unsigned int ) myF<<'\n'; //error?
cout<<" to Float Without Fixed "<<(float) myU<<'\n';//not clear, so have to use fixed
cout<<" to Float With Fixed "<<fixed<<(float) myU<<'\n';//error?
cout<<" difference "<<myF-myU<<'\n'; //error?
cout<<" myU+32 "<<myU+32<<'\n'; //-1+32=31 ==> understandable
}
使用gcc 4.6.3的输出:
myU is 4294967295
back To Long 4294967296
back To unsigned int 0
to Float Without Fixed 4.29497e+09
to Float With Fixed 4294967296.000000
difference 1.000000
myU+32 31
数4294967295
中float (32-bit IEEE 754)
被表示为如下:
0 10011111 00000000000000000000000
sign exponent mantissa
(+1) (2^32) (1.0)
将其转换回整数(在这种情况下为long)的规则是:
sign * (2^exponent) * mantissa
结果将4294967296
是适合long long
您的合适大小,但太大而无法容纳,unsigned int
因此您可以0
进行unsigned int
转化。
注意,问题是与浮动例如表示大量的限制4294967295
和4294967200
两者都表示当它们被存储作为浮子相同的比特。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句