c++ - Save a float into an integer without losing floating point precision -
i want save value of float variable named f
in third element of array named i
in way floating point part isn't wiped (i.e. don't want save 1
instead of 1.5
). after that, complete last line in way see 1.5
in output (don't use cout<<1.5;
or cout<<f;
or similar tricks!)
float f=1.5; int i[3]; i[2] = ... ; cout<<... ;
does have idea?
if can assume int
32 bits can type-punning:
float f = 1.5; int i[3]; i[2] = *(int *)&f; cout << *(float *)&i[2];
but getting undefined behaviour territory (breaking aliasing rules), since accesses type via pointer different (incompatible) type.
Comments
Post a Comment