C Union and simultaneous assignment to members -
this question has answer here:
- floating point numbers not work expected 6 answers
in following code
#include<stdio.h> int main() { union myunion { int intvar; char charvar; float floatvar; }; union myunion localvar; localvar.intvar = 10; localvar.charvar = 'a'; localvar.floatvar = 20.2; printf("%d ", localvar.intvar); printf("%c ", localvar.charvar); printf("%f ", localvar.floatvar); }
i understand union can hold 1 value @ time. when assign char value, int overwritten, n when assign floatvalue, char overwritten. expecting garbage values int , char variables , 20.200000 float variable last value assigned. following output i'm getting on vs express gcc
1101109658 Ü 20.200001
unable understand why float value changed ?
this has nothing union
, , float
value not changed.
it doesn't have enough bits represent 20.2
binary float. that's okay, nobody has many bits.
you should read what every computer scientist should know floating-point arithmetic.
Comments
Post a Comment