浮动到 int 意外行为 [英] float to int unexpected behaviour

查看:29
本文介绍了浮动到 int 意外行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你能解释一下这个程序的 o/p 行为吗?

can you please explain the o/p behavior of this program.

int main()
{
  float a = 12.5;
  printf("%d
", a);
  printf("%d
", *(int *)&a);
  return 0;
} 

您能否在 http://codepad.org/AQRlAzkC 上查看代码
为什么会有这个输出..

can you please check code at http://codepad.org/AQRlAzkC
why is this output coming ..

推荐答案

您不想将浮点指针强制转换为整数指针.浮点数和整数的存储方式不同,如果这样做,则不会发生转换,因此您将在屏幕上打印垃圾.但是,如果您将 int-value 转换为 float-value,则编译器会将 float 从其内部类型转换为整数.所以你应该用 (int) 替换 (int *).

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).

另外,%d 用于十进制(整数)值.你想要的是 %f,它用于浮点值,用于第一个 printf.

Also, %d is for decimal(integer) values. What you want is %f, which is for float values, for the first printf.

你想要的是这个:

#include <stdio.h>

int main()
{
  float a = 12.5;
  printf("%f
", a); //changed %d -> %f
  printf("%d
", (int)a); //changed *(int *)& -> (int) for proper conversion
  return 0;
} 

在此验证:http://codepad.org/QD4kzAC9

这篇关于浮动到 int 意外行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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