Why does printf implicit float to int conversion n

2020-04-18 08:36发布

Please help me in understanding the following C Output:

#include<stdio.h>
int main() {
    float x = 4.0;
    printf("%f\n",x);
    printf("%d\n",x);
    int y=x;
    printf("%d\n",y);
    return 0;
}

Ouput on gcc compiler

4.000000
0
4

As far as i have read when we assign float to an int variable the decimal part of the variable is terminated and then assigned to the int.

Why it is not happening in this case?

标签: c printf
3条回答
霸刀☆藐视天下
2楼-- · 2020-04-18 08:54

floats are automatically promoted to doubles when passed as ... parameters (similarly to how chars and short ints are promoted to ints). When printf() looks at a format specifier (%d or %f or whatever), it grabs and interprets the raw data it has received according to the format specifier (as int or double or whatever) and then prints it.

printf("%d\n",x) is wrong because you are passing a double to printf() but lie to it that it's going to be an int. printf() makes you pay for the lie. It takes 4 bytes (most likely, but not necessarily 4 bytes) from its parameters, which is the size of an int, it grabs those bytes from where you have previously put 8 bytes (again, most likely, but not necessarily 8 bytes) of the double 4.0, of which those 4 bytes happen to be all zeroes and then it interprets them as an integer and prints it. Indeed, powers of 2 in the IEEE-754 double precision format normally have 52 zero bits, or more than 6 8-bit bytes that are zero.

Those "most likely, but not necessarily" words mean that the C standard does not mandate a fixed size and range for types and they may vary from compiler to compiler, from OS to OS. These days 4-byte ints and 8-byte doubles are the most common (if we consider, e.g. the x86 platform).

查看更多
看我几分像从前
3楼-- · 2020-04-18 09:02

You're not printing y, you're printing x again.

As a side note, printf can't do conversions. So passing a float when a %d is expected is undefined behavior.

查看更多
劫难
4楼-- · 2020-04-18 09:07

as far as i have read when we assign float to an int variable the decimal part of the variable is terminated and then assigned to the int.

Statement is correct, but to make this conversion you must cast variable you wish to convert, not just assign it to another int variable.

This causes problems also in the printf statement, since you are printing a float variable with int specifier %d without a cast.

Fix you're code like this:

printf("%d\n", (int) x);
                 ^
                 | this is the cast operation

and it will correctly print integer value 4 for variable x.

查看更多
登录 后发表回答