C型香蕉中的类型转换? [英] Type Conversion in C going Bananas?

查看:51
本文介绍了C型香蕉中的类型转换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎C和我在这里对预期的输出意见不一致.

It seems that C and I disagree on the expected output here.

我有:

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是A:100.000000 B:0,C:1079574528,D:0

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

I expect to get this output as the float should be casted in all three ways to integer:

f是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" 指示符,即对于所有输出和任何其他行为,不仅对于非强制值,任何可预测或可解释行为的结尾.

You have float values and only cast one to int.
You use "%d" specifier for floats, that is the end of any predictable or explainable behaviour, for all the output and any other behaviour, not only for the non-cast values.

( SomeProgrammerDude在评论中指出了speficier与类型之间的对比.我在此处参考spec来添加UB方面.)

这篇关于C型香蕉中的类型转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆