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.

live demo


Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -