十进制数转二进制浮点数
发布网友
发布时间:2022-04-25 21:37
我来回答
共1个回答
热心网友
时间:2022-06-17 17:58
按楼主的要求改完了
#include <math.h>
#include <iostream.h>
#define chang 24
#define fuhao 1 //符号位
#define jieshu 8 //阶数
#define weishu 23 //位数
#define weishuB 32 //尾数
void dayuyizhuanhuan(double shijinshuyoufuhao,int *p);
void main()
{double shijinshu;
int i=0,fudianB[weishuB];
cout<<"请输入一个十进制数"<<endl;
cin>>shijinshu;
//if(fabs(shijinshu)>1)
dayuyizhuanhuan(shijinshu,fudianB);
for(i=0;i<32;i++)
cout<<fudianB[i];
cout<<endl;
}
void dayuyizhuanhuan(double shijinshuyoufuhao,int *p)
{int i=0,j=0,t=0,w=0,x=0,m=0,c=0,guozh[chang],guox[chang],zhengshubufenB[chang],xiaoshubufenB[chang];
double xiaoshubufenD;
int zhengshubufenD;
double shijinshuD;
shijinshuD=fabs(shijinshuyoufuhao);
zhengshubufenD=(int)shijinshuD;
xiaoshubufenD=shijinshuD-zhengshubufenD;
//cout<<zhengshubufenD<<" "<<xiaoshubufenD<<endl;///////
while(zhengshubufenD)//整数部分的转化
{guozh[i]=zhengshubufenD%2;
i++;
zhengshubufenD=zhengshubufenD/2;
}
//cout<<i<<endl;///////
t=i,w=i-1;
for(j=0;j<t;j++)
{zhengshubufenB[j]=guozh[w];
w--;
}
t=weishu-i+1,w=0; //////
//cout<<t<<endl;
while(xiaoshubufenD!=0&&t!=0)//小数部分的转化
{guox[x]=(int)(xiaoshubufenD*2);
//cout<<guox[x];
x++;
xiaoshubufenD=xiaoshubufenD*2-(int)(xiaoshubufenD*2);
t--;
}
//cout<<endl;
//cout<<guox[22]<<" "<<x<<" "<<t<<endl;
m=x,c=0;
//cout<<guox[22]<<endl;
for(j=0;j<m;j++)
{xiaoshubufenB[j]=guox[c];
c++;
}
//cout<<guox[22]<<" "<<c<<" "<<j<<endl;
//int a;//////
//for(a=0;a<x;a++)
//cout<<xiaoshubufenB[a];
//cout<<endl;
int s[fuhao],E[jieshu],guoE[jieshu],jishua=0,jishub=0,jishuc=0,jishud=0;
int ee;
ee=i+127-1;
while(ee)//阶数的转化
{guoE[jishua]=ee%2;
jishua++;
ee=ee/2;
}
if(i==1)
{jishub=jishua,jishuc=jishua-1;
E[jishud]=0;
for(jishud=1;jishud<8;jishud++)
{E[jishud]=guoE[jishuc];
jishuc--;
}
}
else
{
jishub=jishua,jishuc=jishua-1;
for(jishud=0;jishud<jishub;jishud++)
{E[jishud]=guoE[jishuc];
jishuc--;
}
}
if(shijinshuyoufuhao>0)//符号位
s[0]=0;
else
s[0]=1;
int jishue=0,jishuw=0,jishux=0,*q;
q=p;
*q=s[0];
for(q=(p+1);q<=(p+8);q++)//阶数的输入
{*q=E[jishue];
jishue++;
}
if((i+x-1)<23)//尾数的输入
{
if(i>1)
{
for(q=(p+9);q<=(p+8+i-1);q++)
{*q=zhengshubufenB[jishuw+1];
jishuw++;
}
for(q=(p+8+i);q<=(p+8+i-1+x);q++)
{*q=xiaoshubufenB[jishux];
jishux++;
}
for(q=(p+x+8+i);q<=(p+31);q++)
{*q=0;
}
}
else
{
for(q=(p+9);q<=(p+8+x);q++)
{
*q=xiaoshubufenB[jishux];
jishux++;
}
for(q=(p+x+8+1);q<=(p+31);q++)
{*q=0;
}
}
}
else
{for(q=(p+9);q<=(p+8+i-1);q++)
{*q=zhengshubufenB[jishuw+1];
jishuw++;
}
for(q=(p+8+i);q<=(p+8+i-1+x);q++)
{*q=xiaoshubufenB[jishux];
jishux++;
}
}
}