Re: printf("%d",float)



santosh <santosh.k83@xxxxxxxxx> writes:
candy_init@xxxxxxxxx wrote:
I just came across the following program:

#include <stdio.h>
int main()
{
float a = 12.5;
printf("%d\n", a);

printf expects and treats the corresponding argument as a signed int,
while you've passed it a float value.

printf("%d\n", *(int *)&a);

Same as above and an additional problem:
[...]

Not quite. The argument is of type int, so "%d" is the correct
format. The problem, of course, is that obtaining the value of that
argument (evaluating ``*(int *)&a'') invokes undefined behavior.

--
Keith Thompson (The_Other_Keith) kst-u@xxxxxxx <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
.



Relevant Pages

  • Re: Floating Point Approximations.
    ... (chosen as 5 decimal places based on the useful precision of the float ... int main{ ... printf; ... point for using, in certain circumstances, BCD math instead of binary ...
    (comp.databases.theory)
  • Re: Abnormal program termination
    ... foo.c:4: warning: function declaration isn't a prototype ... Your version is legal under C90 rules, but int mainis more explicit ... float ave(), average; ...
    (comp.lang.c)
  • RTF Render with Scale
    ... float fHorzSizeInches = nHorzSize / 25.4f; ... IntPtr hdc = graphics.GetHdc; ... int nHorzSize = SafeNativeMethods.GetDeviceCaps(hdc, ... PHYSICALWIDTH = 110, ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: RAD vs. performance
    ... work with both int and float. ... name (e.g. "+" for both int and float addition). ... Again, it's a compatibility issue. ... contend that assuming interfaces are equivalent and inferring the most ...
    (comp.lang.misc)
  • (part1b) Han from China teaches you C
    ... int flist, mlist, slist; ... float board_size; ... static void draw_tube(float bottom_radius, float top_radius, ... glVertex3f(xmin, ymin, zmax); glVertex3f; ...
    (comp.lang.c)