[英]Why does printf(“value: %f”,10/2); output 0.000000?
我知道整数算术将截断分数,但在这里它至少应打印5。为什么打印0.000000
?
The call of printf
has undefined behavior because the conversion specifier %f
does not correspond to the type of the expression 10 / 2
, which is int
. 调用
printf
具有未定义的行为,因为转换说明符%f
与表达式10 / 2
的类型int
。 As the two operands of the expression 10 / 2
have the type int
, the result has the type int
because it is the common type of the both operands. 作为表达的两个操作数
10 / 2
具有类型int
,结果具有类型int
,因为它是两个操作数的常见的类型。
Use instead at least 10.0 / 2
. 至少使用
10.0 / 2
。 In this case, the expression has the type double
. 在这种情况下,表达式的类型为
double
。
Or output the integer expression 10 /2
using conversion specifier %d
or %i
like 或输出的整数表达式
10 /2
使用转换符%d
或%i
喜欢
printf( "value: %d", 10 / 2 );
From the C Standard (7.21.6.1 The fprintf function) 根据C标准(7.21.6.1 fprintf函数)
9 If a conversion specification is invalid, the behavior is undefined.275) If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined .
9如果转换说明无效,则行为未定义。275) 如果任何参数不是对应转换说明的正确类型,则行为未定义 。
10
and 2
aren't valid float
s. 10
和2
不是有效的float
。 They are int
s. 它们是
int
。
To have your program print correct output, do this: 要使程序打印正确的输出,请执行以下操作:
printf("value:%f",10./2.);
Notice the .
请注意
.
after each number. 每个数字之后。 This signifies to the compiler that the number is a floating-point number.
这向编译器表示该数字是浮点数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.