-6

输出是什么?

main()
{
    float a=4;
    int i=2;
    printf("%f %d",i/a,i/a);
    printf("%d %f",i/a,i/a);
}

我收到的答案是:0.500000 00 0.000000

原因:在第一个printf中, %f=i/a=2/4=int/float隐式转换完成并i成为float导致结果 a float(即 0.500000)。

float 的默认精度为 6,因此十进制后为 6 位,然后是 next %d=i/a=2 /4=0.500000,但%d格式字符串仅打印整数,因此打印 0 并丢弃十进制后的值。

Nextprintf%d=i/a=2/4print 0 具有相同的概念;但是,%f=i/a=2/4=0.000000最后的结果我不明白。

4

3 回答 3

4

This plain undefined behavior to specify the wrong format specifier to printf in both cases the i/a expression will be promoted to double and you are specifying that it is a int for one argument. The C99 draft standard in section 7.19.6.1 The fprintf function which printf's section refers back to for the format string paragraph 9 says:

If a conversion specification is invalid, the behavior is undefined.[...]

You should enable warning but both gcc and clang will warn about this without cranking them up at all, in gcc I obtain the following message:

warning: format ‘%d’ expects argument of type ‘int’, but argument 3 has type ‘double’ [-Wformat]
于 2013-10-01T13:24:18.680 回答
3

i/afloat由于其中一个操作数是 ,因此表达式将始终计算为float。打印时,我们使用说明符%d%f. 所以当我们使用%f它时(应该)总是 0.5 而当我们使用%d它时应该是undefined.

在带有 gcc 编译器的 Linux (ubuntu) 上,我得到以下输出(\n为清楚起见,在第一次打印后添加了一个):

0.500000 2047229448
899608576 0.500000
于 2013-10-01T13:26:23.583 回答
2

Undefined behaviour: all the data types in printf are implicitly floats. This is because i/a has type float as the int datum gets promoted to floating point. So you must use %f exclusively in your printf.

于 2013-10-01T13:24:04.110 回答