gpt4 book ai didi

c - 为什么类型转换从 int 打印为 float "0.0000"

转载 作者:行者123 更新时间:2023-11-30 21:32:27 25 4
gpt4 key购买 nike

下面是我为理解类型转换而编写的一些代码,但我不明白为什么 float 或 double 的值被打印为“0.000000”,即使我从整数数组进行类型转换或尝试从 union 地址进行解释.

#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;

}

最佳答案

首先,intfloat 不是兼容的类型。

在你的代码中,通过说

 f=(float*)(x);

你打破了strict aliasing rule 。任何进一步的使用都会调用 undefined behavior .

简单地说,您不能只获取一个指向 float 的指针,将其转换为 int * 并取消引用该 int * > 获取 int 值。引用wikipedia article ,

[..] pointer arguments in a function are assumed to not alias if they point to fundamentally different types, [...]

有关更详细的说明,请参阅已链接的常见问题解答答案。

关于c - 为什么类型转换从 int 打印为 float "0.0000",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35637097/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com