联合浮点数和整数 [英] Union float and int

查看:40
本文介绍了联合浮点数和整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有点困惑.在开发一个基于预定义参数的函数的过程中,根据类型将所需的确切参数传递给 sprintf 函数,我发现了非常奇怪的行为(例如这是 %f %d 示例"、typeFloat、typeInt).

I'm little bit confused. During development of one function that based on predefined parameters, pass to sprintf function exact parameters needed based on their type, I found really strange behaviour ( something like "This is %f %d example", typeFloat, typeInt ).

请查看以下剥离的工作代码:

Please take a look at following stripped working code:

struct Param {
 enum { typeInt,    typeFloat   } paramType;
 union {
    float f;
    int i;
 };
};

int _tmain(int argc, _TCHAR* argv[])
{
 Param p;
 p.paramType = Param::typeInt;
 p.i = -10;

 char chOut[256];
 printf( "Number is %d\n", p.paramType == Param::typeInt ? p.i : p.f );
 printf( "Number is %f\n", p.paramType == Param::typeInt ? p.i : p.f );
 return 0;
}

我的预期输出是 printf( "Number is %d\n", p.paramType == Param::typeInt ? p.i : p.f );

Number is -10

但它实际上打印了

Number is 0

我在Param p的初始化后放置了一个断点,虽然p.paramType被定义为typeInt,但if的实际输出是 -10.0000.检查 p.f 会按预期给出一些未定义的值,而 p.i 也按预期显示 -10.但是 p.paramType == Param::typeInt ?p.i : p.f 在观察窗口中求值为 -10.000000.

I have put a breakpoint after initialization of the Param p, and although p.paramType is defined as typeInt, actual output for if was -10.0000. Checking p.f gives some undefined value as expected, and p.i shows -10 also as expected. But p.paramType == Param::typeInt ? p.i : p.f in watch window evaluates to -10.000000.

我添加了第二个 printf 将它打印为浮点数,现在输出是

I added second printf that prints it as float and now the output is

Number is 0
Number is -10.000000

那么实际上为什么会发生这种情况?这可能是 Visual Studio 中的错误(我使用的是 VS2012)?

So actually why this happens? Is it possible that this is a bug in Visual Studio (I use VS2012)?

更新:

std::cout<< (p.paramType == Param::typeInt ? p.i : p.f);

给出 -10 的正确值.

gives correct value of -10.

推荐答案

这是因为表达式 p.paramType == Param::typeInt 的结果类型?p.i : p.f 总是浮点数(只有 value 不同,取决于 paramType),但你的第一个格式字符串需要一个整数.

This is because the resulting type of the expression p.paramType == Param::typeInt ? p.i : p.f is always float (only the value is different depending on paramType), but your first format string expects an integer.

以下应该按您的预期工作:

The following should work as you expect:

printf("Number is %d\n", (int)(p.paramType == Param::typeInt ? p.i : p.f));

cout 版本为您提供了预期的输出,因为插入的表达式的类型 (float) 是自动推导出来的,因此它将其格式化为浮点数.它与您的第二个 printf 基本相同.

The cout version gives you the expected output because the type of the expression being inserted (float) is deduced automatically, and so it formats it as a float. It is essentially the same as your second printf.

这篇关于联合浮点数和整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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