Separate the integer and decimal parts of a floating point number.
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}