Why does printf implicit float to int conversion not work?

前端 未结 3 528
暗喜
暗喜 2021-01-25 11:27

Please help me in understanding the following C Output:

#include
int main() {
    float x = 4.0;
    printf(\"%f\\n\",x);
    printf(\"%d\\n\",x);         


        
3条回答
  •  梦毁少年i
    2021-01-25 11:52

    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.

提交回复
热议问题