c++中的浮点数问题

来源:百度知道 编辑:UC知道 时间:2024/05/27 20:50:56
//一个很小的c++程序,解释一下标记处输出的原因(我用的是VC6.0环境),谢谢

#include<iostream>

using namespace std;

int main()
{
float f=34.5;
int *ip=reinterpret_cast<int *>(&f);
cout<<f<<endl;
cout<<*ip<<endl;
*ip=100;
cout<<*ip<<endl;
cout<<f<<endl;//主要是这里的输出结果,麻烦解释下
return 1;
}

//下面是输出的结果
34.5
1107951616
100
1.4013e-043//对应上面需要解释的地方
如果有大侠觉得分少不愿回答的话,分不是问题,只要回答出来,本人分可以随便给。

首先说明一点,*ip和f共用同一个内存空间

#include<iostream>
using namespace std;
void binary_code(int num)
{
for(int i=31;i>=0;--i)
{
printf("%d",(num>>i)&1);
}
cout<<endl;
}
int main()
{
float f=34.5;
int *ip=reinterpret_cast<int *>(&f);
binary_code(*ip);
cout<<"float:"<<f<<endl;
cout<<"int:"<<*ip<<endl;

*ip=100; //varible f has been changed !
puts("\nAfter change\n");
binary_code(*ip);
cout<<"float:"<<f<<endl;
cout<<"int:"<<*ip<<endl;

return 0;
}

#include<iostream>

using namespace std;

typedef union _tagFLOAT
{
struct
{
char a;
char b;
char c;
char d;
};
float data;
}FLOAT;