这个int在C中的float转换有什么问题吗? [英] What is wrong with this int to float conversion in C?

查看:161
本文介绍了这个int在C中的float转换有什么问题吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  float a = 1.32; 
int * b;
b =& a;
printf(%d,* b);

这段代码把float变成了一个int,但是我得到的输出是:1068037571

这与计算机的IEEE 754转换功能有关吗?
Thanks!

解决方案

您的程序调用未定义的行为。您只是将 float 的表示方式重新解释为 int 。您绝对不会将 int 转换为 float 。你不能指望任何特定的行为。



要将float转换为int,您可以使用如下代码:

  int b = a; 

float 截断为 int


I'm confused by the output of the following bit of code:

float a  = 1.32;
int* b;
b= &a;
printf("%d", *b);

This bit of code turns the float into an int, but the output I'm getting is: 1068037571

Is this related to the IEEE 754 converting capabilities of the computer? Thanks!

解决方案

Your program invokes undefined behaviour. You are simply reinterpreting the representation of the float as an int. You are categorically not converting an int to a float. You cannot expect any particular behaviour.

To convert the float into an int you would use code like this:

int b = a;

which truncates the float to an int.

这篇关于这个int在C中的float转换有什么问题吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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