简体   繁体   English

算术表达式为printf arg

[英]Arithmetic expression as printf arg

I am not able to understand why 我不明白为什么

float x = (4+2%-8);
printf("%f\n", x);

prints 6.000000 and 打印600万

printf("%f\n", (4+2%-8));

prints 0.000000. 打印0.000000。 Any information will be helpful. 任何信息都会有所帮助。 Regards. 问候。

The expression (4 + 2 % -8) produces an integer and you are trying to print a float (and they don't match). 表达式(4 + 2 % -8)产生一个整数,并且您尝试打印浮点数(它们不匹配)。

In the first case the integer is converted to float (because of the assignment) so later on the printf works because the value is in a format %f expects. 在第一种情况下,整数将转换为float (由于赋值),因此稍后在printf可以使用,因为该值采用%f期望的格式。

Try this: 尝试这个:

printf("%f\n", (4.0 + 2 % -8));
                 ^

It's because here: 这是因为这里:

float x = (4+2%-8);

The (4+2%-8) is of type int but is converted to float because that's the type of x . (4+2%-8)的类型为int但是由于x的类型而被转换为float However, here: 但是,这里:

printf("%f\n", (4+2%-8));

No cast is performed so you pass an int where it expects a float giving you a garbage value. 没有执行任何强制类型转换,因此您将传递一个int ,该int期望一个float值给您一个垃圾值。 You can fix this with a simple cast: 您可以使用简单的演员表修复此问题:

printf("%f\n", (float)(4+2%-8));

In the first snippet the resulting int value is implicitly converted to float due to assignment, in the second snippet you are lying to the compiler: you tell it to expect a value of type double but "send" a value of type int instead. 在第一个代码段中,由于赋值,结果int值隐式转换为float ,在第二个代码段中,您对编译器撒谎:您告诉它期望使用double类型的值,但“发送”一个int类型的值。

Do not lie to the compiler. 不要骗编译器。 It will get its revenge. 它将报仇。

Note that the printf conversion specifier "%f" expects a value of type double , but "sending" a float is ok because that value is automagically converted to double before the function is called. 请注意, printf转换说明符"%f"期望使用double类型的值,但“发送” float是可以的,因为在调用函数之前,该值会自动转换为double

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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