简体   繁体   中英

Can anyone explain the output

If I try to print a float as an int , this code:

main () {                         
    float a = 6.8f;                      
    printf("%d", a);                      
}                       

prints 1073741824, while this code:

main () {            
    float a = 9.5f;           
    printf("%d", a);            
}                   

prints 0.

Is the output undefined? Also when is %f used with integer and %d used with double?

不仅输出,而且整个程序都有未定义的行为,因为传递给printf()的值的类型与格式字符串期望的类型不匹配。

From the C99 standard section 7.19.6.1 The fprintf function :

If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.

%d expects an int , not a float , so the program has undefined behaviour (including the output).

As described in previous answers if the print format doesn't match the type passed, it shows undefined behavior.

If you want to view integer as float u need to typecast it.

int j = 5;
printf("%f",(float)(j));

This will print output as 5.0 ie as a floating digit number

The C Standard says that the printf format must match the type passed in. If it doesn't, the behavior is expressly undefined:

C99, 7.19.6.1 # 9 (fprintf)

If a conversion specification is invalid, the behavior is undefined.239) If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM