【发布时间】:2014-06-17 18:12:34
【问题描述】:
我尝试了几个关于类型转换的注意事项的示例。我不明白为什么下面的代码 sn-ps 无法输出正确的结果。
/* int to float */
#include<stdio.h>
int main(){
int i = 37;
float f = *(float*)&i;
printf("\n %f \n",f);
return 0;
}
这打印0.000000
/* float to short */
#include<stdio.h>
int main(){
float f = 7.0;
short s = *(float*)&f;
printf("\n s: %d \n",s);
return 0;
}
这打印7
/* From double to char */
#include<stdio.h>
int main(){
double d = 3.14;
char ch = *(char*)&d;
printf("\n ch : %c \n",ch);
return 0;
}
这会打印垃圾
/* From short to double */
#include<stdio.h>
int main(){
short s = 45;
double d = *(double*)&s;
printf("\n d : %f \n",d);
return 0;
}
这打印0.000000
为什么从float 到int 的转换会给出正确的结果,而在显式转换类型时所有其他转换都会给出错误的结果?
我无法清楚地理解为什么需要这种(float*) 的类型转换而不是float
int i = 10;
float f = (float) i; // gives the correct op as : 10.000
但是,
int i = 10;
float f = *(float*)&i; // gives a 0.0000
以上两种类型转换有什么区别?
为什么我们不能使用:
float f = (float**)&i;
float f = *(float*)&i;
【问题讨论】:
-
float f = (float)&i不把i的内存位置分配给f吗? -
您正在转换指针,而不是数值,这意味着您正在处理一种类型的对象(例如
int)好像它们是另一种类型的对象(如float)。结果是垃圾。要转换数值,只需使用int i = 37; float f = i;-- 或者,如果您坚持不必要地明确,请使用float f = (float(i);。 (所有数字类型都可以隐式转换,因此很少需要从一种数字类型转换为另一种。)(float的范围和精度要求不能像 16 位那样窄。)跨度>