Problem description: how to obtain the integer and decimal part of a floating point number
Method 1:
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 disadvantages: the number of digits in decimal places cannot be precise, because the decimal part is obtained by difference, and part of precision is lost.
Method 2:
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 disadvantage: the fractional part cannot obtain the positive and negative numbers of floating point numbers.
Method 3:
1 void floatdata (float f) 2 {3 float fp = f; 4 unsigned char * P = (unsigned char *) & FP; 5 Int nsign = 1; 6 7/* symbol bit */8 If (* (p + 3) & 0x80)/* get the highest bit, if it is 1, it is negative */9 {10 nsign =-1; 11} 12 cout <"symbol bit:" <nsign <Endl; 13 14/* Get level code */15 int hex = (* (p + 2) & 0x80)> 7; 16 hex | = (* (p + 3) & 0x7f) <1); 17 Hex-= 127; 18 cout <"level code: "
Method 4:
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; // if it is not set to 8, the default value is used, the decimal digits are truncated to 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 // integer 24 Pos = Str. find (". "); 25 if (Pos! = String: NPOs) 26 {27 string tstr = Str. substr (0, POS); 28 cout <"INTEGER:" <atof (tstr. c_str () <Endl; 29 STR = Str. substr (Pos, str. length ()-Pos); 30} 31 32 // decimal 33 cout <"decimal: O" <atof (Str. c_str () <Endl; 34}