背景:我在記錄中有一些元素,其中一些元素可以是float,unsigned int或unsigned long long。所以,我雖然使用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
32位[float](https://en.wikipedia.org/wiki/Single-precision_floating-point_format)不能有足夠的精度來存儲32位無符號整數的_exact_值(或者更糟糕的是長長),因爲有效位精度只有24位。嘗試使用double,而不是長整數。 –
注意:「返回無符號整數」行導致未定義的行爲,因爲值超出範圍 –