简体   繁体   English

printf中的C语言计算

[英]C language calculation in printf

#include <stdio.h>

int main(){
int x;
x = (10+20)*(1.0/2);
printf("%d", x);
return 0;
}

the output is 输出是

15

and in another form: 并以另一种形式:

#include <stdio.h>

int main(){
printf("%d", (10+20)*(1.0/2));
}

the output is 输出是

0

1.0/2 is 0.5 when calculate in integer variable x , but 1.0/2 is 0 when calculate in printf with %d (I think...) 在整数变量x计算时, 1.0/20.5 ,而在使用%dprintf进行计算时, 1.0/20 (我认为...)

I cannot understand this situation... 我无法理解这种情况...

In addition, when I change %d to %f in the second code, the output is 15.000000 另外,当我在第二个代码中将%d更改为%f时,输出为15.000000

I'm using DEV C++ in Windows 8. 我在Windows 8中使用DEV C ++。

The type of (10+20)*(1.0/2) is double , but "%d" expects an int . (10+20)*(1.0/2)double ,但是"%d"期望为int

So, you need to cast to int : 因此,您需要转换为int

printf("%d", (int) ((10+20)*(1.0/2)));

It works with "%f" because that expects a double . 它与"%f"因为它需要double

as said before, your problem is casting issues. 如前所述,您的问题在于投放问题。 since 1.0/2 = 0.5 --> it is translated to 0, as a result of int casting. 因为1.0 / 2 = 0.5->由于int强制转换为0。 the right way to do it is either using a calculation function - that returns an integer, casting it to int (as proposed), or doing the calculations before the printf. 正确的方法是使用计算函数-返回整数,将其强制转换为int(如建议的那样),或者在printf之前进行计算。

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

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