C going Bananas 中的类型转换?

Type Conversion in C going Bananas?

我和 C 似乎不同意这里的预期输出。

我有:

struct r_struct {
    int r_i;
    float r_f, r_f2;
};

struct r_struct r;

r.f = 100.0;

[...]
printf("f is A:%f B:%d, C:%d, D:%d\n", r.f, r.f, r.f_lhzr / 1, (int)r.f);

我得到这个输出:

f is A:100.000000 B:0, C:1079574528, D:0

我希望得到这个输出,因为浮点数应该以所有三种方式转换为整数:

f is A:100.000000 B:100, C:100, D:100

这里有人可以解释一下吗?

来自 printf() 的规范,例如https://en.cppreference.com/w/cpp/io/c/fprintf

If any argument after default conversions is not the type expected by the corresponding conversion specifier, or if there are fewer arguments than required by format, the behavior is undefined.

您有浮点值,并且只将一个值转换为 int
您对浮点数使用 "%d" 说明符,即所有输出和任何其他行为的任何可预测或可解释行为的结束,而不仅仅是非强制转换值。

(SomeProgrammerDude 在评论中指出了 specificier 和 type 之间的对比。我在这里参考 spec 添加了 UB 方面。)

好的伙计们。

知道了!非常感谢。

我通过在打印前简单地将浮点数分配给一个整数来解决我的问题。然后 printf 打印出正确的整数。

int i;

i=r.f; // or i=r.f/1; or i=(int)r.f;

printf("Correct float casted to int: %d\n",i);

/* Does NOT work by design. None of these:
printf("Wrong float casted to int: %d\n",r.f);
printf("Wrong float casted to int: %d\n",(int)r.f);
printf("Wrong float casted to int: %d\n",r.f/1);
*/