+ 2

C - Why is output 0.00 instead of 3.00?

#include <stdio.h> union Test { int i; float f; }; int main() { union Test t; t.f = 3.14; t.i = 3; printf("%.2f\n", t.f); return 0; }

26th Jan 2020, 11:39 AM
Paolo De Nictolis
Paolo De Nictolis - avatar
5 odpowiedzi
+ 6
Does it help? https://stackoverflow.com/questions/33445690/union-float-and-int (These C tricks are headache ...)
26th Jan 2020, 11:53 AM
Black Winter
+ 6
The binary representation of a float is entirely different from an int. In this case you're telling printf that it is recieving a float as parameter, yet, you are passing an int into it, so printf tries to interpret an int as a float which makes no sense. An int 1234567890 would have the same binary representation as a 1228890.25 float for example.
26th Jan 2020, 12:10 PM
Dennis
Dennis - avatar