C整数和浮点数除法输出
C integer and float division output
有人可以解释以下代码的输出:
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);
它会按预期工作。
因为您正在除整数而不是尝试打印(整数结果为)浮点值
试试这个
// Example program
#include <stdio.h>
int main()
{
float a = 17, b = 100;
printf("%f\n", 17.0/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.00/100);
return 0;
}
有人可以解释以下代码的输出: 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);
它会按预期工作。
因为您正在除整数而不是尝试打印(整数结果为)浮点值
试试这个
// Example program
#include <stdio.h>
int main()
{
float a = 17, b = 100;
printf("%f\n", 17.0/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.00/100);
return 0;
}