Hello geeks. My teacher gave me horrible homework i can't cope with. He told me to suggest a way to convert floating numbers given in decimal system(ex. 123.456) to hexadecimal system. I know there is a simple way to do it in iostream liblary (setting floatfield flag to hexfloat), but i just don't get this presentation. I tried to understand it, but it seems unnecessary for me. Mz task is to suggest a waz. So, my suggestion is: convert values before and after dot separately and print them in correct order (with dot between them). This is code i made:
#include <iostream>
#include <iomanip>
usingnamespace std;
int main()
{
constint P = 6; // precission
cout << fixed << setprecision(P);
double d1=100.34; // converted number
cout << d1 << endl;
int i1=int(d1); // getting "before dot" part to int.
double d2;
d2=d1-i1; // substracting, to get only "after dot value"
for (int i=0; i<P; ++i)
d2*=10; // multiplying P times to print it correctly
int i2;
i2=int(d2); // getting "after dot" part to second int.
cout << i1 << "." << i2;
// printing together.
cin.get();
}
I haven't use "hex" manipulator during printing to see if everything is correct. Unfortunatelly, it is not. Sometimes in "after dot" section get value one less than proper. I tried to figure out, where is the problem. I found out that CPU approximates double in odd way. How can i correct approximation in my program?
P.S. What should i do with number less that one? Then multiplying section does not work properly.