問題描述:如何將獲取一個浮點數的整數部分以及小數部分
方法一:1 #include <iostream> 2 using namespace std; 3 4 void main() 5 { 6 float f = -23.04f; 7 int i = f; 8 float ff = f - i; 9 10 cout << "i=" << i << ", ff=" << ff << endl; 11 }
output:
i=-23, ff=-0.0400009 缺點:不能夠精確小數的位數,因為小數部分是由差求得,會丟失部分精度。 方法二:1 #include <iostream> 2 #include <sstream> 3 #include <string> 4 using namespace std; 5 6 void main() 7 { 8 float f = -23.04f; 9 int i = 0; 10 float ff = 0.0f; 11 12 stringstream ss; 13 ss << f; 14 ss >> i >> ff; 15 cout << "i=" << i << ", ff=" << ff << endl; 16 }
output:
i=-23, ff=0.04 缺點:小數部分無法獲取浮點數的正負號 方法三:1 void FloatData(float f) 2 { 3 float fp = f; 4 unsigned char *p = ( unsigned char *)&fp; 5 int nSign = 1; 6 7 /*符號位*/ 8 if(*(p+ 3) & 0x80) /*獲取最高位,如果是1則為負*/ 9 { 10 nSign = - 1; 11 } 12 cout << "符號位:" << nSign << endl; 13 14 /*獲取階碼*/ 15 int hex = (*(p+ 2) & 0x80) >> 7; 16 hex |= ((*(p+ 3)& 0x7f) << 1); 17 hex -= 127; 18 cout << "階碼:" << hex << endl; 19 20 /*數據部分*/ 21 unsigned long int l_int = 0L; 22 unsigned char *q = ( unsigned char *)&l_int; 23 24 /*數據拷貝*/ 25 *q = *p; 26 *(q+ 1) = *(p+ 1); 27 *(q+ 2) = *(p+ 2) | 0x80; 28 *(q+ 3) = 0x00; 29 30 /*數據存儲區*/ 31 l_int <<= 8; 32 cout << "整數部分:" ; 33 if(hex >= 0) 34 { 35 cout << (l_int>>( 32- 1-hex)) << endl; 36 } 37 else 38 { 39 l_int >>= -hex; 40 cout << 0 << endl; 41 } 42 43 /*小數部分*/ 44 unsigned long int tmp = 0L; 45 if(hex >= 0) 46 tmp = 1 << ( 32- 1-hex); 47 else 48 tmp = 1 << 31; 49 float sum = 0.0f; 50 for(int i= 0;i< 31;i++) 51 { 52 if((tmp & l_int) && i!= 0) 53 sum += 1 * ( float)pow( 2.0f,-i); 54 tmp >>= 1; 55 } 56 cout << "小數部分:" << sum << endl; 57 }
方法四:
1 #include <iostream> 2 #include <sstream> 3 #include <string> 4 #include <cmath> 5 #include <iomanip> // just for setw() 6 void splitFloat(float f) 7 { 8 stringstream ss; 9 ss << setprecision( 8) << f; // 如果不設置為8,用默認是值,則會截斷小數的位數 10 11 string str; 12 ss >> str; 13 14 size_t pos = str.find( "-"); 15 int nSign = 1; 16 if (pos != string::npos) 17 { 18 nSign = - 1; 19 str = str.substr(pos+ 1, str.length()-pos- 1); 20 } 21 cout << "nSign = " << nSign << endl; 22 23 // 整數 24 pos = str.find( "."); 25 if (pos != string::npos) 26 { 27 string tstr = str.substr( 0, pos); 28 cout << "整數:" << atof(tstr.c_str()) << endl; 29 str = str.substr(pos, str.length()-pos); 30 } 31 32 // 小數 33 cout << "小數:o" << atof(str.c_str()) << endl; 34 }