【发布时间】:2016-02-25 19:58:39
【问题描述】:
下面是我为理解类型转换而编写的一些代码,但我不明白为什么浮点或双精度的值被打印为“0.000000”,即使我从整数数组类型转换或尝试从联合地址解释.
#include <stdio.h>
union test1
{
int x;
float y;
double z;
};
int main()
{
int x[2]={200,300};
float *f;
f=(float*)(x);
printf("%f\n",*f); /*(1)why is this value 0.0*/
*f=(float)(x[0]); /*(2)this works as expected and prints 200.00000*/
printf("%f\n",*f);
union test1 u;
u.x=200;
/*(3)this line give compilation error why*/
//printf ("sizeof(test1) = %d \n", sizeof(test1));
/*(4) this line also prints the value of float and double as 0.0000 why*/
printf ("sizeof(test1) = %lu u.x:%d u.y:%f u.z:%lf \n", sizeof(u), u.x, u.y, u.z);
return 0;
}
【问题讨论】:
-
选择一种语言。不同的语言工作方式不同。
-
标题说“0.0000”。帖子说“0.000000”。建议进行更改,以便它们与您的真实体验相匹配。
-
强制转换不会改变数据,它只会改变数据将被解释为的类型。谷歌搜索一下浮点数据(对于您选择的架构)是如何存储的,您可能会理解得更好。
-
您所做的是未定义的行为 (UB)。使用
"%e"将有助于更好地理解UB,但它仍然是UB。 -
@mah:嗯...不是真的。强制转换很好地改变了值的表示。对于一个指针,它是指针本身的值,而不是它指向的数据的值——这就是这里的问题。 C 没有像 C++ 这样的不同类型转换运算符的动物园。