【发布时间】:2016-04-10 20:36:43
【问题描述】:
背景:我在记录中有一些元素,其中一些元素可以是 float、unsigned int 或 unsigned long long。所以,我想使用 float 作为一个通用值来从读取这些元素的函数返回。
但是,我在从 unsigned int 转换为 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
【问题讨论】:
-
32 位 float 没有足够的精度来存储 32 位无符号整数(或更糟的是 long long)的 exact 值,因为有效位精度是只有 24 位。尝试使用双精度,但不要使用 long long ints。
-
注意:“返回无符号整数”行会导致未定义的行为,因为值超出范围
标签: c++ floating-point type-conversion