#include
int main() {
float a = 1234.5f;
printf(\"%d\\n\", a);
return 0;
}
It displays a 0
!! How is that
That's because %d
expects an int
but you've provided a float.
Use %e
/%f
/%g
to print the float.
On why 0 is printed: The floating point number is converted to double
before sending to printf
. The number 1234.5 in double representation in little endian is
00 00 00 00 00 4A 93 40
A %d
consumes a 32-bit integer, so a zero is printed. (As a test, you could printf("%d, %d\n", 1234.5f);
You could get on output 0, 1083394560
.)
As for why the float
is converted to double
, as the prototype of printf is int printf(const char*, ...)
, from 6.5.2.2/7,
The ellipsis notation in a function prototype declarator causes argument type conversion to stop after the last declared parameter. The default argument promotions are performed on trailing arguments.
and from 6.5.2.2/6,
If the expression that denotes the called function has a type that does not include a prototype, the integer promotions are performed on each argument, and arguments that have type
float
are promoted todouble
. These are called the default argument promotions.
(Thanks Alok for finding this out.)
Since you tagged it with C++ as well, this code does the conversion as you probably expect:
#include <iostream.h>
int main() {
float a = 1234.5f;
std::cout << a << " " << (int)a << "\n";
return 0;
}
Output:
1234.5 1234
It's because of the representation of a float in binary. The conversion to an integer leaves it with 0.
You just need to use the appropriate format specifier (%d,%f,%s,etc.) with the relevant data type (int,float, string, etc.).
hey it had to print something so it printed a 0. Remember in C 0 is everything else!
You want %f not %d