I would like to know why the output in this program is 0.0000:
{
int a = 65;
char c = (char)a;
int m = 3.0/2;
printf("%f\n", 5 / 2);
return (0);
}
I would like to know why the output in this program is 0.0000:
{
int a = 65;
char c = (char)a;
int m = 3.0/2;
printf("%f\n", 5 / 2);
return (0);
}
5 / 2
is integer division which yields an int
result. However the "%f"
printf flag interprets it as a double
value, which will cause undefined behaviour.
In your case, it prints 0.0000, but it could be anything, really.
Use floating point operands in order to get a floating point return value.
printf("%f\n", 5.0 / 2.0);
You are printing a integer with %f
specifier. Keep in mind that when you divide int by another int the result is again int. Thus 5/2
is the integer 2
, which printed with the %f
specifier prints 0.0
. To avoid this use 5.0/2
this time dividing a double by an integer and thus getting a double result.
You are most likey getting a parameter mismatch in:
printf("%f\n", 5 / 2);
This should be written as:
printf("%d\n", 5 / 2); // use "%d" for integer.
Although not completely correct, the rest of your assignment statements do not appear to contribute to your print failure.
As Elias has pointed out in his comment every number is int if stated otherwise. That is the key to solution.
In C/C++ 5/2 is int number and equals 2 That is why your :
printf("%f\n", 5 / 2);
is the same as:
printf("%f\n", 2);
But why it prints 0.0 you ask - here is why. When printf is given '%f' flag it will treat a parameter as float.
Now your code disassembly looks / may look like that:
printf("%f\n", 5 / 2);
push 2
call dword ptr [__imp__printf (0B3740Ch)]
push 2 moves (usually 32bit 0x2) on the stack
And now the most important how 32 bit value=2 looks (in binary):
(MSB) 00000000 00000000 00000000 00000010 (LSB)
and what this pattern means if treated as 32 bit floating point (according to this):
sign(bit #31) = 0
exponent(next 8 bits ie #30..#23) all = 0 too
fraction(the remaining bits) contains 2(dec)
Now the value should in theory be calculated as:
(-1)^0 * (1+1*2^-22)^(0-127) = 1 * (1+2^-22)^-127
BUT exponent=0x0 which is special case (read link) and is treated as 0.0 - period.
No idea what compiler you are using or what options, but try this:
printf("%f\n",(double)(5 / 2));
or this:
printf("%f\n",5.0 / 2.0));
The result of the expression you pass to printf is an integer 0 ('5 / 2' is an integer division). To correct it:
printf("%f\n", (float) 5 / 2);
or
printf("%f\n", 5.0 / 2.0);