Use
printf("%f\n",(float)i);
The compiler do not automatically cast your int to float
Edit:
I think this is an interesting question, so I found a similar article:
Code for printf function in C
Then I tried to explore __printf , vfprintf and ___printf_fp
__printf (const char *format, ...)
{
va_list arg;
int done;
va_start (arg, format);
done = vfprintf (stdout, format, arg);
va_end (arg);
return done;
}
In vfprintf, they define a jump_table, that processes the specific format (%d, %f, %x ...)
static const uint8_t jump_table[] =
{
/* ' ' */ 1, 0, 0, /* '#' */ 4,
0, /* '%' */ 14, 0, /* '\''*/ 6,
0, 0, /* '*' */ 7, /* '+' */ 2,
0, /* '-' */ 3, /* '.' */ 9, 0,
/* '0' */ 5, /* '1' */ 8, /* '2' */ 8, /* '3' */ 8,
/* '4' */ 8, /* '5' */ 8, /* '6' */ 8, /* '7' */ 8,
/* '8' */ 8, /* '9' */ 8, 0, 0,
0, 0, 0, 0,
0, /* 'A' */ 26, 0, /* 'C' */ 25,
0, /* 'E' */ 19, /* F */ 19, /* 'G' */ 19,
0, /* 'I' */ 29, 0, 0,
/* 'L' */ 12, 0, 0, 0,
0, 0, 0, /* 'S' */ 21,
0, 0, 0, 0,
/* 'X' */ 18, 0, /* 'Z' */ 13, 0,
0, 0, 0, 0,
0, /* 'a' */ 26, 0, /* 'c' */ 20,
/* 'd' */ 15, /* 'e' */ 19, /* 'f' */ 19, /* 'g' */ 19,
/* 'h' */ 10, /* 'i' */ 15, /* 'j' */ 28, 0,
/* 'l' */ 11, /* 'm' */ 24, /* 'n' */ 23, /* 'o' */ 17,
/* 'p' */ 22, /* 'q' */ 12, 0, /* 's' */ 21,
/* 't' */ 27, /* 'u' */ 16, 0, 0,
/* 'x' */ 18, 0, /* 'z' */ 13
};
Then they put LABEL in this vfprintf function (something like switch case)
int vfprintf (FILE *s, const CHAR_T *format, va_list ap)
{
...
LABEL (form_percent):
/* Write a literal "%". */
outchar (L_('%'));
break;
LABEL (form_integer):
/* Signed decimal integer. */
base = 10;
LABEL (form_float):
...
}
In Label form_float, they define a struct which defined float format
struct printf_info info = {
.prec = prec,
.width = width,
.spec = spec,
.is_long_double = is_long_double,
.is_short = is_short,
.is_long = is_long,
.alt = alt,
.space = space,
.left = left,
.showsign = showsign,
.group = group,
.pad = pad,
.extra = 0,
.i18n = use_outdigits,
.wide = sizeof (CHAR_T) != 1
};
Finally, they call
int ___printf_fp (FILE *fp,
const struct printf_info *info,
const void *const *args)
to print the output.
Conclusion: if input format is not correct, we wil have a wrong format struct info
, then output must be wrong too.