有人可以解释以下代码的输出: http://cpp.sh/9dy44
为什么最后一行总是0.17?
float a = 17, b = 100;
printf("%f\n", 17/100);
printf("%f\n", a/b);
printf("%f\n", 17/b);
printf("%f\n", 17.0f/b);
printf("%f\n", a/100);
printf("%f\n", a/100.0f);
printf("%f\n", 5/100);
输出
0.000000
0.170000
0.170000
0.170000
0.170000
0.170000
0.170000
最佳答案
这叫做Undefined Behaviour
,不要试图理解为什么会这样,因为顾名思义,它是undefined
!。发生未定义的行为是因为您正在尝试打印 double 但您传递的是两个整数。请注意,您还会收到警告:
14:25: warning: format '%f' expects argument of type 'double', but argument 2 has type 'int' [-Wformat=]
将最后一行改为:
printf("%f\n", 5.0/100);
它会按预期工作。
关于C整数和 float 除法输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53031631/