浮动到意想不到的行为 [英] float to int unexpected behaviour
问题描述
int main()
{
float a = 12.5;
printf(%d \ n,a);
printf(%d \ n,*(int *)& a);
返回0;
$ / code>
您可以在 http://codepad.org/AQRlAzkC
为什么会输出这个结果..
您不希望将浮点指针转换为整型指针。浮点数和整数的存储方式并不相同,如果这样做,则不会进行转换,因此会将垃圾打印到屏幕上。但是,如果你将一个int值赋给一个浮点值,那么编译器会将浮点值从内部类型转换为一个整数。所以你应该用(int)
替换(int *)
。
另外,%d
是十进制(整数)值。你想要的是%f
,这是浮动值,对于第一个 printf
。
$ p $ #include< stdio .H>
int main()
{
float a = 12.5;
printf(%f \ n,a); //改变%d - > %f
printf(%d \ n,(int)a); //改变*(int *)& - > (int)进行正确的转换
return 0;
}
经过验证: http://codepad.org/QD4kzAC9
can you please explain the o/p behavior of this program.
int main()
{
float a = 12.5;
printf("%d\n", a);
printf("%d\n", *(int *)&a);
return 0;
}
can you please check code at http://codepad.org/AQRlAzkC
why is this output coming ..
You don't want to cast the float pointer to an integer pointer. Floats and integers are not stored the same way and if you do that then there is no conversion that will take place, and thus you will get garbage printed to the screen. If however you cast an int-value to a float-value then the compile will convert the float from it's internal type into an integer for you. So you should replace the (int *)
with (int)
.
Also, %d
is for decimal(integer) values. What you want is %f
, which is for float values, for the first printf
.
What you want is this:
#include <stdio.h>
int main()
{
float a = 12.5;
printf("%f\n", a); //changed %d -> %f
printf("%d\n", (int)a); //changed *(int *)& -> (int) for proper conversion
return 0;
}
verified here: http://codepad.org/QD4kzAC9
这篇关于浮动到意想不到的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!