这里不考虑负整数的情况,只考虑正整数。
void trans(char a[], int num)
{
if(num<0)
{
cout<<"negetive!"<<endl;
return;
}
int index = 0;
for(int temp = num;temp!=0;temp=temp/2)
{
a[index] = temp%2 + '0';
++index;
}
a[index] = '\0';
// 逆置
char tempa[index];
for(int i=0;i<index;i++)
{
tempa[i] = a[index-i-1];
}
for(int i=0;i<index;i++)
{
a[i] = tempa[i];
}
}
int main()
{
ofstream outfile("binary.txt");
if(!outfile)
{
cout<<"无法打开文件!"<<endl;
return 2;
}
int n = -1;
cout<<"你想输入几个正整数:";
cin>>n;
if(n<0)
return 2;
cout<<endl;
int num = -1;
char binary[1000] = {'\0'};
for(int i=0;i<n;i++)
{
cout<<"请输入正整数:";
cin>>num;
if(num<0)
{
cout<<"请不要输入负数!"<<endl;
i--;
continue;
}
trans(binary,num);
cout<<endl<<"对应的二进制数为:"<<binary<<endl;
outfile<<binary<<endl;
}
}